我有一个基本的SpringBoot应用程序。使用Spring初始化器、嵌入式Tomcat、Thymeleaf模板引擎,并将其打包为可执行JAR文件。
我想保护一个控制器:
@Controller
@RequestMapping("/company")
@RolesAllowed({"ROLE_ADMIN"})
@PreAuthorize("hasRole('ADMIN')")
@Secured("ADMIN")
public class CompanyController {
}
我知道有不同的选择但我真的不知道我应该使用
所有的@PreAuthorize
、@R药品
和@安全
都是允许配置方法安全性的注释。它们可以应用于单个方法或类级别,在后一种情况下,安全约束将应用于类中的所有方法。
方法级安全性是使用SpringAOP代理实现的。
@PreAuthorize
注解允许使用Spring表达式语言(SpEL)指定对方法的访问约束。这些约束在方法执行之前进行评估,如果不满足约束,可能会导致方法被拒绝执行。@PreAuthorize
注解是Spring Security框架的一部分。
为了能够使用@PreAuthorize
,@EnableGlobalFacodSecurity
注释中的prePostEnable
属性需要设置为true
:
@EnableGlobalMethodSecurity(prePostEnabled=true)
@R订定
注解起源于JSR-250Java安全标准,该注解比@PreAuthorize
注解更受限制,因为它只支持基于角色的安全性。
为了使用@R药品
注解,包含此注解的库需要在类路径上,因为它不是Spring Security的一部分。此外,@EnableGlobalMedicodSecurity
注解的jsr250Enable
属性需要设置为true
:
@EnableGlobalMethodSecurity(jsr250Enabled=true)
@安全
注解是一个遗留的Spring Security 2注解,可用于配置方法安全性。它不仅支持基于角色的安全性,但不支持使用Spring表达式语言(SpEL)来指定安全约束。建议在新应用程序中使用@PreAuthorize
注解。
需要在@EnableGlobalFacodSecurity
注释中使用securedEn的
属性显式启用对@Sec的
注释的支持:
@EnableGlobalMethodSecurity(securedEnabled=true)
下表显示了可与Spring Security 5一起使用的安全注释中对Spring表达式语言的支持:
╔═════════════════════╦═══════════════════╗
║ Security Annotation ║ Has SpEL Support? ║
╠═════════════════════╬═══════════════════╣
║ @PreAuthorize ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PostAuthorize ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PreFilter ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @PostFilter ║ yes ║
╠═════════════════════╬═══════════════════╣
║ @Secured ║ no ║
╠═════════════════════╬═══════════════════╣
║ @RolesAllowed ║ no ║
╚═════════════════════╩═══════════════════╝
@安全
和@可转录
在Spring中执行相同的功能。不同之处在于@安全
是Spring特定的注释,而@可转录
是Java标准注释(JSR250)。这两种注释都不支持SpEL。
@PreAuthorize
是另一个Spring特定的注释。您可以使用SpEL使用@PreAuthorize
执行更强大的操作。您可以根据角色/权限、当前经过身份验证的用户和传递给方法的参数编写限制方法调用的表达式。
@PreAuthorize("hasRole('ADMIN') or #user.id == authentication.name")
public void deleteUser(User user) {
...
}
http://docs.spring.io/autorepo/docs/spring-security/4.0.x/reference/html/el-access.html#el-common-built-in
至于使用哪个,真的取决于你。@Secure
和@PreAuthorize
会将你的代码绑定到Spring。如果绑定到Spring不是问题或者你需要执行更强大的操作,请使用@PreAuthorize
。
所有这些对于您的目的基本上是相同的,但是@PreAuthorize
最适合控制器和控制器方法。@安全
和@可旋转
旨在描述服务层安全属性。
还要注意@PreAuthorize
注释要工作,您必须定义一个配置类:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
...
}