安全注释
所有@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 ║
╚═════════════════════╩═══════════════════╝