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

标签 spring-boot spring-security

我无法在 @PreAuthorize 注释中使用 hasRole 方法。另外 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 Security Reference :

46.3.3 What does "ROLE_" mean and why do I need it on my role names?

Spring Security has a voter-based architecture which means that an access decision is made by a series of AccessDecisionVoters. The voters act on the "configuration attributes" which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value. The most common voter is the RoleVoter which by default votes whenever it finds an attribute with the "ROLE_" prefix. It makes a simple comparison of the attribute (such as "ROLE_USER") with the names of the authorities which the current user has been assigned. If it finds a match (they have an authority called "ROLE_USER"), it votes to grant access, otherwise it votes to deny access.

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

相关文章:

java - 我们如何在 Spring Boot Filter 中获取和设置响应体

java - Spring-boot 安全记住我 token 不起作用

spring-mvc - Spring MVC 4 全局基本 HTTP 身份验证

java - Spring 安全许可证全部不起作用

spring - 在 application.yml 中定义基本安全用户、密码和角色

spring - 我该如何打包jar,以便依赖的spring jar不会包含在我的最终jar中,而是将其引用到Maven存储库

postgresql - 创建指向现有实例的 bluemix postgresql 服务

java - 由 : com. fastxml.jackson.core.JsonParseException : Unrecognized token 'Employee' : was expecting ('true' , 'false' 或 'null' 引起的错误)

java - 无法通过 spring-boot 应用程序访问 Angular 页面

java - 有没有办法在没有 Spring 安全的情况下使用 Spring 过滤器链?