spring-security如何授予ACL权限

Pet*_*ete 11 permissions acl spring-security

我目前正在将spring-security集成到我们的新Web应用程序堆栈中.我们需要能够为用户或角色授予访问特定对象或特定类型的所有对象的权限.然而,在处理文档和示例时,我没有真正得到的一件事:

ACL是仅为单个对象的用户/角色授予权限还是为整个类型执行此操作?据我所知,它domain object意味着类型,但示例和教程似乎为特定对象分配权限.我只是困惑或者我可以两个都做?如果没有,我该怎么办?

谢谢!

Vla*_*kov 25

有了spring-security,你可以做到这两点.这是可能的,因为spring-security支持所谓的权限规则 - 在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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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>
    
    Run Code Online (Sandbox Code Playgroud)