簡體   English   中英

刪除彈簧安全角色

[英]Remove spring security role

有沒有辦法撤銷彈簧安全角色? 具體來說,我想從UserDetails.getAuthorities()對象中刪除元素

Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
authorities.remove(new SimpleGrantedAuthority("ROLE_TO_BE_REMOVED"));

該代碼將被成功編譯,但是在調用remove時將引發UnsupportedOperationException 問題在於標准的身份驗證實現可確保getAuthorities返回的Collections $UnmodifiableRandomAccessList<E>是不可修改的(它返回Collections $UnmodifiableRandomAccessList<E> )。

因此,我需要的是除去角色的其他方法,或者繞過Collection不變性的方法。

使用的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);
}   

我猜你需要使用org.springframework.security.provisioning.UserDetailsManager.updateUser()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM