Reputation: 1566
Dear all I am using spring 5 and like to have the ROLE_ prefix removed. Thereforre I used "grantedAuthorityDefaults" and set the role prefix to "". Unfortunatley when I call later on SecurityContextHolder.getContext().getAuthentication().getAuthorities()
on a page without login (Public acces) than I still get values with "ROLE_" prefix "ROLE_ANONYMOUS" and my mapping logic in the JSON Rest controller Advice fails.
Any hits at which other places I ned to declare the ROLE prefix = "" ?
@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class WebSecurityJwtConfiguration extends WebSecurityConfigurerAdapter {
...
@Bean
public GrantedAuthorityDefaults grantedAuthorityDefaults() {
return new GrantedAuthorityDefaults("");
}
...
}
@RestControllerAdvice
public class CoreSecurityJsonViewControllerAdviceimplements ResponseBodyAdvice<Object> {
protected void beforeBodyWriteInternal(MappingJacksonValue mappingJacksonValue, MediaType mediaType, MethodParameter methodParameter, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
// HERE I still get values with "ROLE_" prefix
Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
Class prioritizedJsonView = this.getJsonViews(authorities);
if (prioritizedJsonView != null) {
mappingJacksonValue.setSerializationView(prioritizedJsonView);
}
}
}
protected Class getJsonViews(Collection<? extends GrantedAuthority> authorities) {
Optional var10000 = authorities.stream().map(GrantedAuthority::getAuthority).map(Role::valueOf).max(Comparator.comparing(Enum::ordinal));
Map var10001 = View.MAPPING;
var10001.getClass();
return (Class)var10000.map(var10001::get).orElse((Object)null);
}
@Override
protected Class getJsonViews(Collection<? extends GrantedAuthority> authorities) {
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.map(Role::valueOf)
.max(Comparator.comparing(Role::ordinal))
.map(View.MAPPING::get)
.orElse(null);
}
}
Upvotes: 2
Views: 659
Reputation: 3724
Yes, that is because the AnonymousAuthenticationFilter Spring Security uses has the "ROLE_ANONYMOUS" hardcoded inside.
You can change that behavior with this override in your WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http.anonymous().authorities("ANONYMOUS"); // or your custom role
}
Upvotes: 3