我无法使用 hasRole
@PreAuthorize
中的方法注释。还有 request.isUserInRole(“ADMIN”)
给 false
.我错过了什么?
虽然 .hasAuthority(“ADMIN”)
工作正常。
我正在为数据库中的用户分配权限。
最佳答案
您必须使用前缀 ROLE_
命名您的权限使用 isUserInRole
,见 Spring Security Reference :
The HttpServletRequest.isUserInRole(String) will determine if
SecurityContextHolder.getContext().getAuthentication().getAuthorities()
contains aGrantedAuthority
with the role passed intoisUserInRole(String)
. Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the following:boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");
与
hasRole
相同(还有 hasAnyRole
),见 Spring Security Reference :Returns
true
if the current principal has the specified role. By default if the supplied role does not start with 'ROLE_' it will be added. This can be customized by modifying thedefaultRolePrefix
onDefaultWebSecurityExpressionHandler
.
关于spring-boot - Spring Boot Security hasRole 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946473/