安全注解
@PreAuthorize
、@RolesAllowed
和@Secured
都是注解,允许配置方法安全。它们既可以应用于单个方法,也可以应用于类级别,在后一种情况下,安全约束将应用于类中的所有方法。
使用Spring AOP代理实现了方法级安全。
@PreAuthorize
@PreAuthorize
注解允许使用Spring表达式语言(SpEL)来指定对方法的访问限制。这些限制在方法执行之前进行评估,如果不满足约束条件,则可能导致拒绝执行该方法。 @PreAuthorize
注解是Spring Security框架的一部分。
为了能够使用@PreAuthorize
,需要将@EnableGlobalMethodSecurity
注解中的prePostEnabled
属性设置为true
:
@EnableGlobalMethodSecurity(prePostEnabled=true)
@RolesAllowed
@RolesAllowed
注释源于Java安全标准JSR-250。与@PreAuthorize
注释相比,此注释的功能更为有限,因为它仅支持基于角色的安全性。
要使用@RolesAllowed
注释,需要将包含该注释的库放在类路径中,因为它不是Spring Security的一部分。此外,@EnableGlobalMethodSecurity
注释的jsr250Enabled
属性需要设置为true
:
@EnableGlobalMethodSecurity(jsr250Enabled=true)
@Secured
@Secured
注释是一个可以用于配置方法安全性的旧版 Spring Security 2 注释。它支持多种安全性而不仅仅是基于角色的安全性,但不支持使用Spring表达式语言(SpEL)指定安全性约束。建议在新应用程序中使用@PreAuthorize
注释而不是此注释。
需要在@EnableGlobalMethodSecurity
注释中显式启用对@Secured
注释的支持,使用securedEnabled
属性:
@EnableGlobalMethodSecurity(securedEnabled=true)
哪些安全注释允许使用SpEL
下表展示了Spring Security 5中可用于安全注释的Spring表达式语言支持:
╔═════════════════════╦═══════════════════╗
║ Security Annotation ║ Has SpEL Support? ║
╠═════════════════════╬═══════════════════╣
║ @PreAuthorize ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PostAuthorize ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PreFilter ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PostFilter ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @Secured ║ no ║
╠═════════════════════╬═══════════════════╣
║ @RolesAllowed ║ no ║
╚═════════════════════╩═══════════════════╝
@RolesAllowed("ADMIN")
和@Secured("ROLE_ADMIN")
。(参见此链接。) - Leponzo