2014-07-13 129 views
1

我有一個Spring Security的角色層次設置是這樣的:訪問Spring Security的角色層次結構編程方式

ROLE_ADMIN > ROLE_MANAGER 
ROLE_MANAGER > ROLE_USER 
ROLE_USER > ROLE_GUEST 

我發現自己需要創建一個VetoableChangeListener,可以否決基於角色對PropertyChangeEvents(由於其中的一個愚蠢的傳統設計問題)。

因此,在我的vetoableChange()方法中,需要根據層次結構否決更改。例如,某個字段不能被定義層次結構中ROLE_MANAGER下面的任何角色所改變,因此如果ROLE_USER嘗試更改它,則會引發PropertyVetoException。

public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { 

    String role = SecurityContextHolder.getContext().getAuthentication().getRoles().get(0); 
    String propertyName = evt.getPropertyName(); 
    String requiredRole = getRequiredRole(propertyName); 

    // determine if the current role is equal to or greater than 
    // the required role, throw PropertyVetoException if not 

} 

任何人都可以協助嗎?

回答

4

在您的聽衆中直接使用您定義的RoleHierarchy

Collection<? extends GrantedAuthority> roles = Collections.singletonList(new SimpleGrantedAuthority(userRole)); 
Collection<? extends GrantedAuthority> reachableRoles = roleHierarchy.getReachableGrantedAuthorities(roles); 

if (reachableRoles.contains(requiredRole)) { 
    // allow 
} else { 
    // deny 
} 

方法getReachableGrantedAuthorities(Collection<? extends GrantedAuthority>)返回一個所有可達權限的數組。可訪問權限是直接分配的權限,以及角色層次結構中所有可從中(可傳遞)訪問的權限。

實施例:

角色層次結構:ROLE_A> ROLE_B和ROLE_B> ROLE_C。

直接分配權限:ROLE_A。

可達到的權限:ROLE_A,ROLE_B,ROLE_C。

相關問題