Nuñ*_*ada 13 spring spring-mvc spring-security spring-boot
我有一个基本的SpringBoot应用程序.使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎和包作为可执行的JAR文件.
我想保护一个控制器:
@Controller
@RequestMapping("/company")
@RolesAllowed({"ROLE_ADMIN"})
@PreAuthorize("hasRole('ADMIN')")
@Secured("ADMIN")
public class CompanyController {
}
Run Code Online (Sandbox Code Playgroud)
我知道有不同的选择,但我真的不知道应该使用哪种
Dim*_*San 31
所有@PreAuthorize,@RolesAllowed和@Secured都是允许配置方法安全性的注释。它们可以应用于单个方法或类级别,在后一种情况下,安全约束将应用于类中的所有方法。
方法级别的安全性是使用Spring AOP 代理完成的。
@PreAuthorize@PreAuthorize注释允许使用Spring 表达式语言 (SpEL)指定对方法的访问约束。这些约束在执行方法之前进行评估,如果不满足约束,可能会导致方法的执行被拒绝。该@PreAuthorize注释是Spring安全框架的一部分。
为了能够使用@PreAuthorize,注解中的prePostEnabled属性
@EnableGlobalMethodSecurity需要设置为true:
@EnableGlobalMethodSecurity(prePostEnabled=true)
Run Code Online (Sandbox Code Playgroud)
@RolesAllowed@RolesAllowed注释起源于JSR-250 Java 安全标准。这个注解比注解更受限制,@PreAuthorize因为它只支持基于角色的安全性。
为了使用@RolesAllowed注解,包含这个注解的库需要在类路径上,因为它不是 Spring Security 的一部分。另外,注解的jsr250Enabled属性@EnableGlobalMethodSecurity需要设置为true:
@EnableGlobalMethodSecurity(jsr250Enabled=true)
Run Code Online (Sandbox Code Playgroud)
@Secured@Securedannotation 是一个遗留的 Spring Security 2 annotation,可用于配置方法安全性。它不仅支持基于角色的安全性,而且不支持使用 Spring 表达式语言 (SpEL) 来指定安全性约束。建议@PreAuthorize在新应用中使用该注解而不是此注解。
为支持@Secured需要在明确启用注释
@EnableGlobalMethodSecurity使用注释securedEnabled属性:
@EnableGlobalMethodSecurity(securedEnabled=true)
Run Code Online (Sandbox Code Playgroud)
下表显示了可与 Spring Security 5 一起使用的安全注释中对 Spring Expression Language 的支持:
???????????????????????????????????????????
? Security Annotation ? Has SpEL Support? ?
???????????????????????????????????????????
? @PreAuthorize ? yes ?
???????????????????????????????????????????
? @PostAuthorize ? yes ?
???????????????????????????????????????????
? @PreFilter ? yes ?
???????????????????????????????????????????
? @PostFilter ? yes ?
???????????????????????????????????????????
? @Secured ? no ?
???????????????????????????????????????????
? @RolesAllowed ? no ?
???????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
Jas*_*ite 14
@Secured并@RolesAllowed在Spring中执行相同的功能.不同之处在于它@Secured是一个特定于Spring的注释,@RolesAllowed而是一个Java标准注释(JSR250).这些注释中的任何一个都不支持SpEL.
@PreAuthorize是另一个Spring特定的注释.@PreAuthorize使用SpEL 可以执行更强大的操作.您可以根据角色/权限,当前经过身份验证的用户以及传递给方法的参数来编写表达式limit方法调用.
@PreAuthorize("hasRole('ADMIN') or #user.id == authentication.name")
public void deleteUser(User user) {
...
}
Run Code Online (Sandbox Code Playgroud)
至于使用哪个,这取决于你. @Secure并将@PreAuthorize你的代码绑定到Spring.如果绑定到Spring不是问题,或者您需要执行更强大的操作,请使用@PreAuthorize.
所有这些对于您的目的来说基本相同,但@PreAuthorize最适合控制器和控制器方法。@Secured并且@RolesAllowed用于描述服务层安全属性。
另请注意,@PreAuthorize要使注释起作用,您必须定义一个配置类:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3885 次 |
| 最近记录: |