文章目录
前言
在上一篇文章已经介绍了springSecurity的使用了,本篇文章主要介绍一下使用spring EL表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限
常见的表达式
Spring Security可用表达式对象的基类是SecurityExpressionRoot
表达式 | 描述 |
hasRole([role]) | 用户拥有指定的角色时返回true(hasRole()默认会将配置中的 role 带有 ROLE_ 前缀再和用户的角色权限 进行对比) |
hasAnyRole([role1,role2]) | 用户拥有任意一个指定中的角色时返回true |
hasAuthority([auth]) | 同hasRole()但不添加前缀 ROLE_ |
hasAnyAuthority([auth1,auth2]) | 同hasAnyRole([auth1,auth2]),但不添加前缀 ROLE_ |
permitAll | 永远返回true |
denyAll | 永远返回false |
anonymous | 当前用户时 anonymous(匿名、未认证)时返回true |
rememberMe | 当前用户时 rememberMe(记住登录) 时发挥true |
authentication | 当前登录用户的 authentication 对象 |
fullAuthticated | 当前用户既不是 anonymous 也不是 rememberMe 时返回true(即正常认证登录时返回true) |
hasIpAddress("192.168.1.0/24") | ip匹配时返回true |
如果需要移除hasRole的前缀,在security配置类中添加如下代码
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults(){
return new GrantedAuthorityDefaults("");//remove the ROLE_ prefix
}
URL安全表达式
http.antMatchers("/test/*").access("hasRole('ADMIN') or hasRole('USER')")
.anyRequest().authenticated();
这里我们定义了 /test/
URL的范围,只有拥有 ADMIN
或 USER
权限的用户可以访问 /test/
匹配的URL
在Web 安全表达式中引用Bean自定义鉴权
http.antMatchers("/test/*").access("hasRole('ADMIN