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.
As said in the comments, you have to use
hasAuthority("ADMIN")instead ofhasRole("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
Role as Authority