Security注解:@PreAuthorize,@PostAuthorize, @Secured, EL实现方法安全

说明

(1)JDK版本:1.8

(2)Spring Boot 2.0.6

(3)Spring Security 5.0.9

(4)Spring Data JPA 2.0.11.RELEASE

(5)hibernate5.2.17.Final

(6)MySQLDriver 5.1.47

(7)MySQL 8.0.12

需求缘起

       在之前的章节中我们介绍过通过注解的方式进行权限的控制了,这里再详细的讲解下方法级安全的几个注解。

一、注解式方法级安全开启

       需要在WebSecuirtyConfig添加配置:

@Configuration
@EnableWebSecurity //启用Spring Security.

////会拦截注解了@PreAuthrize注解的配置.
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

}

二、允许的注解

       这里主要@PreAuthorize, @PostAuthorize, @Secured这三个注解可以使用。

2.1 @Secured

       当@EnableGlobalMethodSecurity(securedEnabled=true)的时候,@Secured可以使用:

@GetMapping("/helloUser")
@Secured({"ROLE_normal","ROLE_admin"})
public String helloUser() {
    return "hello,user";
}

说明:拥有normal或者admin角色的用户都可以方法helloUser()方法。另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“

       如果我们要求,只有同时拥有admin & noremal的用户才能方法helloUser()方法,这时候@Secured就无能为力了。

2.2 @PreAuthorize

       Spring的 @PreAuthorize/@PostAuthorize 注解更适合方法级的安全,也支持Spring 表达式语言,提供了基于表达式的访问控制。

       当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize可以使用:

@GetMapping("/helloUser")
@PreAuthorize("hasAnyRole('normal','admin')")
public String helloUser() {
    return "hello,user";
}

说明:拥有normal或者admin角色的用户都可以方法helloUser()方法。

       此时如果我们要求用户必须同时拥有normal和admin的话,那么可以这么编码:

@GetMapping("/helloUser")
@PreAuthorize("hasRole('normal') AND hasRole('admin')") 
public String helloUser() {
    return "hello,user";
}

       此时如果使用user/123登录的话,就无法访问helloUser()的方法了。

2.3 @PostAuthorize

       @PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值的权限,Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject。

当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PostAuthorize可以使用:

@GetMapping("/helloUser")
@PostAuthorize(" returnObject!=null &&  returnObject.username == authentication.name")
public User helloUser() {
        Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user;
        if("anonymousUser".equals(pricipal)) {
            user = null;
        }else {
            user = (User) pricipal;
        }
        return user;
}

       这三个最常用也就是@PreAuthorize这个注解了,在使用中主要是配合Spring EL表达式。

原文地址:https://www.cnblogs.com/ysyy/p/10708645.html