spring - @RolesAllowed 与 @PreAuthorize 与 @Secured

标签 spring spring-mvc spring-boot spring-security

我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎,并打包为可执行 JAR 文件。

我想保护 Controller :

@Controller
@RequestMapping("/company")
@RolesAllowed({"ROLE_ADMIN"})
@PreAuthorize("hasRole('ADMIN')")
@Secured("ADMIN")
public class CompanyController {
}

我知道有不同的选择,但我真的不知道我应该使用哪个

最佳答案

安全注释

所有@PreAuthorize@RolesAllowed@Secured 都是允许配置方法安全性 的注解。它们可以应用于单个方法或类级别,在后一种情况下,安全约束将应用于类中的所有方法。

使用 Spring AOP proxies 实现方法级别的安全性.

@PreAuthorize

@PreAuthorize 注释允许使用 Spring 表达式语言 (SpEL) 指定对方法的访问约束。这些约束在方法被执行之前被评估,如果约束没有被满足,可能会导致方法的执行被拒绝。 @PreAuthorize 注释是 Spring Security 框架的一部分。

为了能够使用@PreAuthorizeprePostEnabled属性在 @EnableGlobalMethodSecurity注解需要设置为true:

@EnableGlobalMethodSecurity(prePostEnabled=true)

@RolesAllowed

@RolesAllowed 注释起源于 JSR-250 Java 安全标准。这个 注释@PreAuthorize 注释更受限制,因为它只支持基于角色的安全性

为了使用 @RolesAllowed 注释,包含此注释的库需要位于类路径中,因为它不是 Spring Security 的一部分。另外,@EnableGlobalMethodSecurity注解的jsr250Enabled属性需要设置为true:

@EnableGlobalMethodSecurity(jsr250Enabled=true)

@Secured

@Secured 注解是遗留的 Spring Security 2 注解,可用于配置方法安全性。它不仅支持基于角色的安全性,而且不支持使用 Spring 表达式语言 (SpEL) 来指定安全性约束。建议在新的应用程序中使用 @PreAuthorize 注释而不是这个注释。

@Secured 注释的支持需要在 使用 securedEnabled 属性的 @EnableGlobalMethodSecurity 注释:

@EnableGlobalMethodSecurity(securedEnabled=true)

哪些安全注解允许使用 SpEL

下表显示了可与 Spring Security 5 一起使用的安全注解中对 Spring Expression Language 的支持:

╔═════════════════════╦═══════════════════╗
║ Security Annotation ║ Has SpEL Support? ║
╠═════════════════════╬═══════════════════╣
║  @PreAuthorize      ║        yes        ║
╠═════════════════════╬═══════════════════╣
║  @PostAuthorize     ║        yes        ║
╠═════════════════════╬═══════════════════╣
║  @PreFilter         ║        yes        ║
╠═════════════════════╬═══════════════════╣
║  @PostFilter        ║        yes        ║
╠═════════════════════╬═══════════════════╣
║  @Secured           ║        no         ║
╠═════════════════════╬═══════════════════╣
║  @RolesAllowed      ║        no         ║
╚═════════════════════╩═══════════════════╝

关于spring - @RolesAllowed 与 @PreAuthorize 与 @Secured,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961625/

相关文章:

java - Spring MVC 在下一页传递 null 值

spring - 如何使用spring data solr实现自动完成

spring-mvc - Spring Boot 4 不渲染 JSP 抛出 404

java - 如何获取 Spring REST 文件下载以返回 404?

java - 使用 spring-boot-2.2.1 删除 HATEOAS 链接中的 _embedded

java - 无法在 Spring/Postman 中上传多部分文件和 dto 对象内容类型 'application/octet-stream' 不受支持

Spring Boot不等待请求

java - 尝试在 spring mvc 中创建并保存对象列表

spring - 如何修复 Spring Boot 一对多双向无限循环?

javascript - 未从异步 XmlHttpRequest 发送或接收文件