Reputation: 814
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.
Upvotes: 2
Views: 5057
Reputation: 62466
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.
Upvotes: 3