2011-09-20 127 views
11

我目前正在將spring-security集成到我們的新Web應用程序堆棧中。我們需要能夠授予用戶或角色訪問特定對象或特定類型的所有對象的權限。然而,這是我在處理文檔和示例時沒有得到的一件事:spring-security ACL如何授予權限

ACL是否僅爲單個對象授予用戶/角色的權限,還是僅爲整個類型授予權限?據我瞭解,domain object意味着類型,但例子和教程看起來像他們分配權限的特定對象。我只是困惑,還是我可以同時做?如果不是,我該怎麼做另一個?

謝謝!

回答

24

隨着彈簧安全,你可以做到這一點。這是可能的,因爲spring-security支持所謂的權限規則 - 在彈簧安全術語中,他們稱之爲權限評估者。權限規則包含ACL,但也可以在對象處於特定狀態時保護對象的實例...等。

這是它如何工作的:

  1. 您需要延長PermissionEvaluator - 這可以讓你有超強的自定義邏輯來確定訪問權限 - 你可以檢查對象的類型或檢驗特定ID,或檢查用戶調用的方法是創建對象,等:

    public class SomePermissionsEvaluator implements PermissionEvaluator { 
        @Override 
        public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { 
         if (permission.equals("do_something") && 
         /*authentication authorities has the role A*/) { 
          return true 
         } else if (permission.equals("do_something_else") && 
         /*authentication authorities has the role B*/) { 
          return /*true if targetDomainObject satisfies certain condition*/; 
         } 
    
         return false; 
        } 
    
        @Override 
        public boolean hasPermission(Authentication authentication, 
         Serializable targetId, String targetType, Object permission) { 
        throw new UnsupportedOperationException(); 
        } 
    } 
    
  2. 現在,你有一個安全規則的用戶,你需要通過註釋應用它:

    @PreAuthorize("hasRole('SOME_ROLE_OR_RIGHT') and" + 
    " hasPermission(#someDomainObject, 'do_something')") 
    public void updateSomeDomainObject(SomeDomainObject someDomainObject) { 
        // before updating the object spring-security will check the security rules 
    } 
    
  3. 爲了這個工作的安全註解應在applicationContext.xml中啓用:

    <global-method-security secured-annotations="enabled" pre-post-annotations="enabled"> 
        <expression-handler ref="expressionHandler"/> 
    </global-method-security> 
    
    <beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"> 
        <beans:property name="permissionEvaluator"> 
         <beans:bean id="permissionEvaluator" class="com.npacemo.permissions.SomePermissionsEvaluator"/> 
        </beans:property> 
    </beans:bean> 
    
+0

啊,感謝您的快速答覆,沒想到它會所以很容易實現PermissionEvaluator在'AclPermissionEvaluator'實現中使用某種'ObjectIdentityRetrievalStrategy' ... – Pete

+0

您可以使列表和代碼突出顯示,只需添加四個額外的空格。我編輯這篇文章作爲例子,看到源。 :) –

+0

我現在看到。非常感謝! –