spring-boot - Spring Boot Security hasRole 不起作用

标签 spring-boot spring-security

我无法使用 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 a GrantedAuthority with the role passed into isUserInRole(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 the defaultRolePrefix on DefaultWebSecurityExpressionHandler.

关于spring-boot - Spring Boot Security hasRole 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946473/

相关文章:

java - 从测试用例调用 Controller 时,使用自动连线组件测试 Controller 为空

java - 具有路径变量参数的 Spring Security

java - 无法解析 Spring Boot 应用程序中的符号 "security"

java - Spring Cloud Zuul Proxy 背后的 Spring OAuth 授权服务器

spring - Autowiring 到 JPA 转换器

java - 本地主机 Spring Boot 中的错误 404

java - Spring Boot 验证信息未显示在 Swagger UI 中

java - 使用自定义用户对象时的 Spring session redis

spring - 具有Spring-Boot/安全性的Null @AuthenticationPrincipal

java - Spring security OAuth2 刷新 token - IllegalStateException,需要 UserDetailsS​​ervice