I am using spring boot 3 and spring security 6 and trying to configure authorization but not able to get it working. I am seeing some weird behaviour which I am not able to understand.
I have configured authorization using following code
http.authorizeHttpRequests(authrorize -> authrorize.requestMatchers("/hello/**").hasRole("USER"));
but after login I get 403 Forbidden error.
I checked the spring security logs and I can see following in the logs:
2024-06-15T06:55:20.123+05:30 DEBUG 15236 — [spring-authn-authz] [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=com.nagpal.spring_authn_authz.config.EmployeeUserDetails@2af776cf, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=846F84FABBD0F9B98EFEF4DAAE047AA4], Granted Authorities=[USER]]]
Granted authority of USER is present but I am still getting 403 error.
After some search I found that, my authorities need to be prepended by “ROLE_”, so I tried to append “ROLE_” prefix to the role from my UserDetails object:
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
log.info("Adding role with ROLE_ appended");
GrantedAuthority role = new SimpleGrantedAuthority("ROLE_" + employee.getRole());
authorities.add(role);
return authorities;
}
after this change, when I try to access the endpoint, I still get 403 Forbidden error but this in logs I can see ROLE_ prefix is appended twice:
2024-06-15T06:59:28.747+05:30 DEBUG 15236 — [spring-authn-authz] [nio-8080-exec-4] w.c.HttpSessionSecurityContextRepository : Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=com.nagpal.spring_authn_authz.config.EmployeeUserDetails@2af776cf, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=846F84FABBD0F9B98EFEF4DAAE047AA4], Granted Authorities=[ROLE_ROLE_USER]]]
I am unable to understand this behaviour. If i don’t append “ROLE_” in my UserDetails objects it does not come at all but If i configure it it comes twice.
Can someone help me understand this?