亲爱的,我正在使用spring 5,并且希望删除ROLE_前缀。因此,我使用了"grantedAuthorityDefaults“,并将角色前缀设置为"”。不幸的是,当我稍后在没有登录(公共访问)的页面上调用SecurityContextHolder.getContext().getAuthentication().getAuthorities()时,仍然会得到带有"ROLE_“前缀"ROLE_ANONYMOUS”的值,而我在JSON控制器建议中的映射逻辑也会失败。
我在其他地方声明角色前缀= "“的地方有什么问题吗?
@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);
}
}发布于 2020-03-20 14:52:52
是的,这是因为AnonymousAuthenticationFilter Spring Security使用的是"ROLE_ANONYMOUS“硬编码的。
您可以在WebSecurityConfigurerAdapter中使用此覆盖来更改该行为。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.anonymous().authorities("ANONYMOUS"); // or your custom role
}https://stackoverflow.com/questions/60764288
复制相似问题