SpringBoot+Spring Security权限认证之@EnableGlobalMethodSecurity三方法详解


@EnableGlobalMethodSecurity三方法详解

要开启Spring方法级安全,在添加了@Configuration注解的类上再添加@EnableGlobalMethodSecurity注解即可

/**
 * spring security配置
 * @EnableGlobalMethodSecurity  要开启Spring方法级安全
 *   prePostEnabled: 确定 前置注解[@PreAuthorize,@PostAuthorize,..] 是否启用
 *   securedEnabled: 确定安全注解 [@Secured] 是否启用
 *   jsr250Enabled: 确定 JSR-250注解 [@RolesAllowed..]是否启用
 *   @RolesAllowed 注解过滤权限
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter

其中注解@EnableGlobalMethodSecurity有几个方法:

  • prePostEnabled 确定 前置注解[@PreAuthorize,@PostAuthorize,..] 是否启用
  • securedEnabled 确定安全注解 [@Secured] 是否启用
  • jsr250Enabled 确定 JSR-250注解 [@RolesAllowed..]是否启用

在同一个应用程序中,可以启用多个类型的注解,但是只应该设置一个注解对于行为类的接口或者类。如:

  • 一个程序启用多个类型注解:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled = true))
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        ...
    }
    

    在调用的接口或方法使用如下:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        ...
    }
    

    在调用的接口或方法使用:

    // 只能user角色可以访问
    @PreAuthorize ("hasAnyRole('user')")
    // user 角色或者 admin 角色都可访问
    @PreAuthorize ("hasAnyRole('user') or hasAnyRole('admin')")
    // 同时拥有 user 和 admin 角色才能访问
    @PreAuthorize ("hasAnyRole('user') and hasAnyRole('admin')")
    // 限制只能查询 id 小于 10 的用户
    @PreAuthorize("#id < 10")
    User findById(int id);
    
    // 只能查询自己的信息
     @PreAuthorize("principal.username.equals(#username)")
    User find(String username);
    
    // 限制只能新增用户名称为abc的用户
    @PreAuthorize("#user.name.equals('abc')")
    void add(User user)
    
  • @PostAuthorize 该注解使用不多,在方法执行后再进行权限验证。 适合验证带有返回值的权限。Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject。如:

    // 指定过滤的参数,过滤偶数
    @PreFilter(filterTarget="ids", value="filterObject%2==0")
    public void delete(List<Integer> ids, List<String> username)
    
  • @PostFilter 对集合类型的返回值进行过滤,移除结果为false的元素

    public interface UserService {
        List<User> findAllUsers();
    
        @PostAuthorize ("returnObject.type == authentication.name")
        User findById(int id);
    
        @PreAuthorize("hasRole('ADMIN')")
        void updateUser(User user);
        
        @PreAuthorize("hasRole('ADMIN') AND hasRole('DBA')")
        void deleteUser(int id);
    }
    

    启用jsr250Enabled

    jsr250Enabled注解比较简单,只有

    • @DenyAll 拒绝所有访问
    • @RolesAllowed({"USER", "ADMIN"}) 该方法只要具有"USER", "ADMIN"任意一种权限就可以访问。这里可以省略前缀ROLE_,实际的权限可能是ROLE_ADMIN
    • @PermitAll 允许所有访问
    本文引用一下作者

    作者:zenghi
    链接:https://www.jianshu.com/p/77b4835b6e8e
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。