阅读完需:约 1 分钟
方法安全
SpringSecurity除了可以配置登录这些之外还可以给方法加密,限制访问方法,只有规定的人才可以访问这个角色。
通常采用的三个注解,就是@Secured(), @PreAuthorize() 及 @RolesAllowed()。
@PreAuthorize(): pre-post-annotations
要使用这个方法安全需要注解来开启,因为默认是关闭的
@EnableGlobalMethodSecurity(prePostEnabled =true,securedEnabled = true)
开启后就可以使用了 例子:
@Service
public class MethodSerice {
// @Service("amdin")
// @PreAuthorize("hasAnyRole('amdin','user')") //admin 和 user 这两角色都可以访问这个方法
@PreAuthorize("hasRole('admin')") //要有admin这个角色才可以访问这个方法
private String admin(){
return "hello admin";
}
}
@Secured(): secured_annotation
@Secured({"ROLE_ADMIN"})
public void changePassword(String username, String password);
使用时,需要如下配置Spring Security (无论是通过xml配置,还是在Spring boot下,直接注解配置,都需要指明secured-annotations)
XML: <global-method-security secured-annotations="enabled"/>
Spring boot: @EnableGlobalMethodSecurity(securedEnabled = true)
@RolesAllowed(): jsr250-annotations
@RolesAllowed({"ROLE_ADMIN"})
public void changePassword(String username, String password);
使用时,需要如下配置Spring Security (无论是通过xml配置,还是在Spring boot下,直接注解配置,都需要指明jsr250-annotations)
XML: <global-method-security jsr250-annotations="enabled"/>
Spring boot: @EnableGlobalMethodSecurity(jsr250Enabled = true)
方法授权类型 | 声明方式 | JSR标准 | 允许SpEL表达式 |
---|---|---|---|
@PreAuthorize、@PostAuthorize | 注解 | No | Yes |
@RolesAllowed、@PermitAll、@DenyAll | 注解 | Yes | No |
@Secure | 注解 | No | No |
protect-pointcut | XML | No | No |