”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Spring 中使用 @Secured 注解的方法安全性

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

发布于2024-07-31
浏览:896

Method security with @Secured Annotation in Spring

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

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

示例场景

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

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

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

运营角色

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

  • ROLE_USER、ROLE_ADMIN

读书:

  • ROLE_USER、ROLE_ADMIN

更新:

  • ROLE_ADMIN

删除:

  • ROLE_ADMIN

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

添加 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 注解!敬请关注!

跟我来!

版本声明 本文转载于:https://dev.to/tiuwill/method-security-with-secured-annotation-in-spring-1hgk?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在C中的显式删除 在C中的动态内存分配时,开发人员通常会想知道是否有必要在heap-procal extrable exit exit上进行手动调用“ delete”操作员,但开发人员通常会想知道是否需要手动调用“ delete”操作员。本文深入研究了这个主题。 在C主函数中,使用了动态分配变量(H...
    编程 发布于2025-07-03
  • 编译器报错“usr/bin/ld: cannot find -l”解决方法
    编译器报错“usr/bin/ld: cannot find -l”解决方法
    错误:“ usr/bin/ld:找不到-l “ 此错误表明链接器在链接您的可执行文件时无法找到指定的库。为了解决此问题,我们将深入研究如何指定库路径并将链接引导到正确位置的详细信息。添加库搜索路径的一个可能的原因是,此错误是您的makefile中缺少库搜索路径。要解决它,您可以在链接器命令中添加...
    编程 发布于2025-07-03
  • Go web应用何时关闭数据库连接?
    Go web应用何时关闭数据库连接?
    在GO Web Applications中管理数据库连接很少,考虑以下简化的web应用程序代码:出现的问题:何时应在DB连接上调用Close()方法?,该特定方案将自动关闭程序时,该程序将在EXITS EXITS EXITS出现时自动关闭。但是,其他考虑因素可能保证手动处理。选项1:隐式关闭终止数...
    编程 发布于2025-07-03
  • 如何将PANDAS DataFrame列转换为DateTime格式并按日期过滤?
    如何将PANDAS DataFrame列转换为DateTime格式并按日期过滤?
    将pandas dataframe列转换为dateTime格式示例:使用column(mycol)包含以下格式的以下dataframe,以自定义格式:})指定的格式参数匹配给定的字符串格式。转换后,MyCol列现在将包含DateTime对象。 date oped filtering > = p...
    编程 发布于2025-07-03
  • 为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    为什么在我的Linux服务器上安装Archive_Zip后,我找不到“ class \” class \'ziparchive \'错误?
    Class 'ZipArchive' Not Found Error While Installing Archive_Zip on Linux ServerSymptom:When attempting to run a script that utilizes the ZipAr...
    编程 发布于2025-07-03
  • 您如何在Laravel Blade模板中定义变量?
    您如何在Laravel Blade模板中定义变量?
    在Laravel Blade模板中使用Elegance 在blade模板中如何分配变量对于存储以后使用的数据至关重要。在使用“ {{}}”分配变量的同时,它可能并不总是最优雅的解决方案。幸运的是,Blade通过@php Directive提供了更优雅的方法: $ old_section =“...
    编程 发布于2025-07-03
  • C++20 Consteval函数中模板参数能否依赖于函数参数?
    C++20 Consteval函数中模板参数能否依赖于函数参数?
    [ consteval函数和模板参数依赖于函数参数在C 17中,模板参数不能依赖一个函数参数,因为编译器仍然需要对非contexexpr futcoriations contim at contexpr function进行评估。 compile time。 C 20引入恒定函数,必须在编译时进行...
    编程 发布于2025-07-03
  • 如何解决AppEngine中“无法猜测文件类型,使用application/octet-stream...”错误?
    如何解决AppEngine中“无法猜测文件类型,使用application/octet-stream...”错误?
    appEngine静态文件mime type override ,静态文件处理程序有时可以覆盖正确的mime类型,在错误消息中导致错误消息:“无法猜测mimeType for for file for file for [File]。 application/application/octet...
    编程 发布于2025-07-03
  • 如何在Java字符串中有效替换多个子字符串?
    如何在Java字符串中有效替换多个子字符串?
    在java 中有效地替换多个substring,需要在需要替换一个字符串中的多个substring的情况下,很容易求助于重复应用字符串的刺激力量。 However, this can be inefficient for large strings or when working with nu...
    编程 发布于2025-07-03
  • 人脸检测失败原因及解决方案:Error -215
    人脸检测失败原因及解决方案:Error -215
    错误处理:解决“ error:((-215)!empty()in Function Multultiscale中的“ openCV 要解决此问题,必须确保提供给HAAR CASCADE XML文件的路径有效。在提供的代码片段中,级联分类器装有硬编码路径,这可能对您的系统不准确。相反,OPENCV提...
    编程 发布于2025-07-03
  • 如何在Java中正确显示“ DD/MM/YYYY HH:MM:SS.SS”格式的当前日期和时间?
    如何在Java中正确显示“ DD/MM/YYYY HH:MM:SS.SS”格式的当前日期和时间?
    如何在“ dd/mm/yyyy hh:mm:mm:ss.ss”格式“ gormat 解决方案: args)抛出异常{ 日历cal = calendar.getInstance(); SimpleDateFormat SDF =新的SimpleDateFormat(“...
    编程 发布于2025-07-03
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-07-03
  • Python中何时用"try"而非"if"检测变量值?
    Python中何时用"try"而非"if"检测变量值?
    使用“ try“ vs.” if”来测试python 在python中的变量值,在某些情况下,您可能需要在处理之前检查变量是否具有值。在使用“如果”或“ try”构建体之间决定。“ if” constructs result = function() 如果结果: 对于结果: ...
    编程 发布于2025-07-03
  • 如何使用Depimal.parse()中的指数表示法中的数字?
    如何使用Depimal.parse()中的指数表示法中的数字?
    在尝试使用Decimal.parse(“ 1.2345e-02”中的指数符号表示法表示的字符串时,您可能会遇到错误。这是因为默认解析方法无法识别指数符号。 成功解析这样的字符串,您需要明确指定它代表浮点数。您可以使用numbersTyles.Float样式进行此操作,如下所示:[&& && && ...
    编程 发布于2025-07-03
  • 如何将多种用户类型(学生,老师和管理员)重定向到Firebase应用中的各自活动?
    如何将多种用户类型(学生,老师和管理员)重定向到Firebase应用中的各自活动?
    Red: How to Redirect Multiple User Types to Respective ActivitiesUnderstanding the ProblemIn a Firebase-based voting app with three distinct user type...
    编程 发布于2025-07-03

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3