0

0

Spring 中使用 @Secured 注解的方法安全性

WBOY

WBOY

发布时间:2024-07-12 09:31:02

|

708人浏览过

|

来源于dev.to

转载

spring 中使用 @secured 注解的方法安全性

该注解提供了一种为业务方法添加安全配置的方法。

它将使用角色来检查用户是否有权限调用该方法。注解是 spring security 的一部分。因此,要启用它的使用,您需要 spring security 依赖项。

示例场景

您有一个具有产品 crud 的应用程序。在此 crud 中,您希望使用两个特定角色来控制操作。

  • 用户:可以创建产品并查看产品。但无法更新或删除产品。
  • 管理员:可以进行所有用户操作,还可以更新和删除产品。

您可以使用@secured 来管理这些角色对每个操作的访问权限。

运营角色

我们可以在示例场景中定义以下角色。

  • role_user、role_admin

阅读:

  • role_user、role_admin

更新:

  • role_admin

删除:

  • role_admin

让我们看一个代码示例并观察应用程序的行为。

千博购物系统.Net
千博购物系统.Net

千博购物系统.Net能够适合不同类型商品,为您提供了一个完整的在线开店解决方案。千博购物系统.Net除了拥有一般网上商店系统所具有的所有功能,还拥有着其它网店系统没有的许多超强功能。千博购物系统.Net适合中小企业和个人快速构建个性化的网上商店。强劲、安全、稳定、易用、免费是它的主要特性。系统由C#及Access/MS SQL开发,是B/S(浏览器/服务器)结构Asp.Net程序。多种独创的技术使

下载

添加 spring security 依赖

要使用 @secured 注解,请为 spring security 添加 maven 依赖项:


    org.springframework.boot
    spring-boot-starter-security

使用@secured注释方法

我们用 @secured 注释方法,定义哪些角色可以访问方法行为。

public class product {

    private long id;
    private string name;
    private bigdecimal value;

    //getters and setters
}

@service
public class productservice {

    @secured({"role_user", "role_admin"})
    public product createproduct(product product) {
        // logic for creating a product
        return product;
    }

    @secured({"role_user", "role_admin"})
    public product getproductbyid(long id) {
        // logic for fetching a product
        return null;
    }

    @secured("role_admin")
    public product updateproduct(product product) {
        // logic for updating a product
        return product;
    }

    @secured("role_admin")
    public void deleteproduct(long id) {
        // logic for deleting a product
    }
}

应用配置

您需要添加@enableglobalmethodsecurity(securedenabled = true)来配置您的spring应用程序以使用@secured启用方法安全性。

@springbootapplication
@enabletransactionmanagement
@enableglobalmethodsecurity(securedenabled = true)
public class masteryapplication {

    public static void main(string[] args) {
        springapplication.run(masteryapplication.class, args);
    }

}

测试行为

在我们的示例中,我们将使用测试来测试行为,因此我们添加 spring boot 测试依赖项。


    org.springframework.security
    spring-security-test
    test


然后我们创建测试来验证是否使用模拟用户并为其分配特定角色,我们可以测试每个角色中的用户以及我们的应用程序的行为方式。通过这样做,我们可以确保只有正确的角色才能执行允许的操作。

@SpringBootTest
class ProductServiceTests {

    @Autowired
    private ProductService productService;

    @Test
    @WithMockUser(roles = "USER")
    void testCreateProductAsUser() {
        Product product = new Product();
        assertDoesNotThrow(() -> productService.createProduct(product));
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testCreateProductAsAdmin() {
        Product product = new Product();
        assertDoesNotThrow(() -> productService.createProduct(product));
    }

    @Test
    @WithAnonymousUser
    void testCreateProductAsAnonymous() {
        Product product = new Product();
        assertThrows(AccessDeniedException.class, () -> productService.createProduct(product));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testGetProductByIdAsUser() {
        assertDoesNotThrow(() -> productService.getProductById(1L)); // Assuming product with ID 1 exists
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testGetProductByIdAsAdmin() {
        assertDoesNotThrow(() -> productService.getProductById(1L));
    }

    @Test
    @WithAnonymousUser
    void testGetProductByIdAsAnonymous() {
        assertThrows(AccessDeniedException.class, () -> productService.getProductById(1L));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testUpdateProductAsUser() {
        Product product = new Product();
        assertThrows(AccessDeniedException.class, () -> productService.updateProduct(product));
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testUpdateProductAsAdmin() {
        Product product = new Product();
        assertDoesNotThrow(() -> productService.updateProduct(product));
    }

    @Test
    @WithAnonymousUser
    void testUpdateProductAsAnonymous() {
        Product product = new Product();
        assertThrows(AccessDeniedException.class, () -> productService.updateProduct(product));
    }

    @Test
    @WithMockUser(roles = "USER")
    void testDeleteProductAsUser() {
        assertThrows(AccessDeniedException.class, () -> productService.deleteProduct(1L));
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void testDeleteProductAsAdmin() {
        assertDoesNotThrow(() -> productService.deleteProduct(1L));
    }

    @Test
    @WithAnonymousUser
    void testDeleteProductAsAnonymous() {
        assertThrows(AccessDeniedException.class, () -> productService.deleteProduct(1L));
    }
}

就是这样,现在您可以使用带有 @secured 注释的角色来管理用户对应用程序的访问。

如果你喜欢这个话题,记得关注我。在接下来的几天里,我将详细解释 spring 注解!敬请期待!

跟我来!

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

106

2025.08.06

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

389

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

68

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

34

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

114

2025.12.24

Java Maven专题
Java Maven专题

本专题聚焦 Java 主流构建工具 Maven 的学习与应用,系统讲解项目结构、依赖管理、插件使用、生命周期与多模块项目配置。通过企业管理系统、Web 应用与微服务项目实战,帮助学员全面掌握 Maven 在 Java 项目构建与团队协作中的核心技能。

0

2025.09.15

Golang 性能分析与pprof调优实战
Golang 性能分析与pprof调优实战

本专题系统讲解 Golang 应用的性能分析与调优方法,重点覆盖 pprof 的使用方式,包括 CPU、内存、阻塞与 goroutine 分析,火焰图解读,常见性能瓶颈定位思路,以及在真实项目中进行针对性优化的实践技巧。通过案例讲解,帮助开发者掌握 用数据驱动的方式持续提升 Go 程序性能与稳定性。

9

2026.01.22

html编辑相关教程合集
html编辑相关教程合集

本专题整合了html编辑相关教程合集,阅读专题下面的文章了解更多详细内容。

53

2026.01.21

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
SQL 教程
SQL 教程

共61课时 | 3.5万人学习

Spring中文手册
Spring中文手册

共0课时 | 0人学习

马士兵spring视频教程
马士兵spring视频教程

共25课时 | 9.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号