我有一个基本的 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 框架的一部分。
为了能够使用@PreAuthorize
,prePostEnabled
属性在
@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/