Springboot Security hasRole not working

ghz 1years ago ⋅ 1952 views

Question

I’m unable to use hasRole method in @PreAuthorize annotation. Also request.isUserInRole(“ADMIN”) gives false. What am I missing? Although .hasAuthority(“ADMIN”) works fine.

I am assigning authorities to the users from a database.


Answer

You have to name your authority with prefix ROLE_ to use isUserInRole, see [Spring Security Reference](https://docs.spring.io/spring- security/site/docs/current/reference/htmlsingle/#servletapi-user-in-role):

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");

Same for hasRole (also hasAnyRole), see [Spring Security Reference](https://docs.spring.io/spring- security/site/docs/current/reference/htmlsingle/#el-common-built-in):

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.

See also [Spring Security Reference](https://docs.spring.io/spring- security/site/docs/5.0.2.RELEASE/reference/htmlsingle/):

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.