2

I'm using a custom UserDetailService which works fine for authentication. The problem is that I can't use role-based constraints.

It's odd that I get the correct authorities from the Controller:

public ModelAndView getMembers(HttpServletRequest request, Authentication auth) 
{
   if(auth != null)
   {
      for (GrantedAuthority ga : auth.getAuthorities())
      {
         // works find and logs "ADMIN", btw. I'm using SimpleGrantedAuthority
         this.logger.debug("0{}", ga);
      }
   }
}

But with the configuration

http
   .csrf().disable()
   .authorizeRequests()
   .antMatchers("/Admin/**").hasRole("ADMIN")
   …

The user can't access pages at e.g. /Admin/Member.

Same goes for thymeleaf-security-tags, e.g.

<div sec:authorize="isAuthenticated() && hasRole('ADMIN')">Hello Admin!</div>

doesn't show "Hello Admin!" for users where the Controller logs authority "ADMIN".

I'm guess I'm missing something or using something wrong.

Thanks for your time and help.

3
  • 2
    Did you try hasRole('ROLE_ADMIN') or use hasAuthority('ADMIN') Commented Mar 17, 2019 at 19:36
  • Thanks, hasRole('ROLE_ADMIN') doesn't work but the hasAuthority('ADMIN')-approach works like a charm … in thymeleaf-security and in spring configuration. Does anyone knows how to set principal's roles in a custom UserDetailService. Commented Mar 17, 2019 at 19:50
  • 1
    Close this question and open a new one Commented Mar 18, 2019 at 5:05

1 Answer 1

3

As said in the comments, you have to use hasAuthority("ADMIN")instead of hasRole("ADMIN").

It's important to make the distinction between Granted Authorities and Roles. There is an article from Baeldung explaining it: Granted Authority Versus Role in Spring Security. From this article we can understand the difference:

GrantedAuthority

In Spring Security, we can think of each GrantedAuthority as an individual privilege. Examples could include READ_AUTHORITY, WRITE_PRIVILEGE, or even CAN_EXECUTE_AS_ROOT. [...]

When using a GrantedAuthority directly, such as through the use of an expression like hasAuthority(‘READ_AUTHORITY’), we are restricting access in a fine-grained manner.

Role as Authority

Similarly, in Spring Security, we can think of each Role as a coarse-grained GrantedAuthority that is represented as a String and prefixed with “ROLE“. When using a Role directly, such as through an expression like hasRole(“ADMIN”), we are restricting access in a coarse-grained manner.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.