我试图更改当前登录用户的权限,但我无法使其正常工作。
我关注这篇文章(在底部,OP声称找到了解决方案):http://forum.spring.io/forum/spring-projects/security/60663-change-user-logged-authorities-on-the-fly
我的UserDetails :: getAuthorities的实现根据用户的内部状态生成权限集合,并返回它(我不使用属性来保存它):
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
if (... some condition ...) {
authorities.add(new SimpleGrantedAuthority("ROLE_A"));
} else {
authorities.add(new SimpleGrantedAuthority("ROLE_B"));
}
return authorities;
}
我刷新权限的代码:
System.out.println(SecurityContextHolder.getContext().getAuthentication().getAuthorities());
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
UserDetails user = userDetailsService.loadUserByUsername("john.doe@example.com");
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
context.setAuthentication(newAuthentication);
SecurityContextHolder.setContext(context);
System.out.println(SecurityContextHolder.getContext().getAuthentication().getAuthorities());
控制台输出(这是预期的):
[ROLE_A]
[ROLE_B]
问题:新权限不会保留。当我稍后调用服务时,权限是[ROLE_A],而不是[ROLE_B]。