Spring Security - @PreAuthorize安全表达式hasRole、hasAuthority区别

hasRole:

角色授权:授权代码,在我们返回的UserDetails的Authority需要加ROLE_前缀,Controller上使用时不要加前缀;

hasAuthority:

权限授权:用户自定义的权限,返回的UserDetails的Authority只要与这里匹配就可以,这里不需要加ROLE_,名称保持一至即可

另外的安全表达式还有:

表达式 说明
permitAll 永远返回true
denyAll 永远返回false
anonymous 当前用户是anonymous时返回true
rememberMe 当前用户是rememberMe用户时返回true
authenticated 当前用户不是anonymous时返回true
fullAuthenticated 当前用户既不是anonymous也不是rememberMe用户时返回true
hasRole(role) 用户拥有指定的角色权限时返回true
hasAnyRole([role1,role2]) 用户拥有任意一个指定的角色权限时返回true
hasAuthority(authority) 用户拥有指定的权限时返回true
hasAnyAuthority([authority1,authority2]) 用户拥有任意一个指定的权限时返回true
hasIpAddress('192.168.1.0') 请求发送的Ip匹配时返回true

还可以在WebSecurity指定我们自己写的方法控制权限:

.access("@MyRbacService.findAuthority(request,authentication)")//指定我们自己写的方法控制权限

参考链接:https://www.baeldung.com/spring-security-expressions

猜你喜欢

转载自blog.csdn.net/qq_26878363/article/details/103632459