有没有办法撤销春保的角色?具体来说,我想从UserDetails.getAuthorities()
对象中移除元素
Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
authorities.remove(new SimpleGrantedAuthority("ROLE_TO_BE_REMOVED"));
此代码将被成功编译,但在调用remove时将抛出
UnsupportedOperationException
。问题是,标准身份验证实现确保getauthorities返回的集合是不可修改的(它返回Collections $UnmodifiableRandomAccessList<E>
)。所以我需要一些其他方法来移除角色,或者绕过集合不变性。
使用的Spring版本:3.2.2.release,Spring安全版本:3.1.3.release
最佳答案
这应该可以做到:
public void removeRole(String role){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> updatedAuthorities =
auth.getAuthorities().stream()
.filter(r -> !role.equals(r.getAuthority()))
.collect(Collectors.toList());
Authentication newAuth = new UsernamePasswordAuthenticationToken(
auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);
SecurityContextHolder.getContext().setAuthentication(newAuth);
}