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.

Flocke
  • 764
  • 6
  • 14
  • 2
    Did you try hasRole('ROLE_ADMIN') or use hasAuthority('ADMIN') – Sully Mar 17 '19 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. – Flocke Mar 17 '19 at 19:50
  • 1
    Close this question and open a new one – Sully Mar 18 '19 at 05:05

1 Answers1

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.

Community
  • 1
  • 1
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240