Spring Security如何授予ACL权限

11

我目前正在将Spring Security集成到我们的新Web应用程序堆栈中。 我们需要能够授予用户或角色访问特定对象或所有特定类型对象的权限。 但是,当我在阅读文档和示例时,有一件事我真的没有弄清楚:

ACL是否只为单个对象授予用户/角色权限,还是为整个类型授予权限? 换句话说,域对象指的是类型,但示例和教程似乎将权限分配给特定的对象。 我是不是混淆了,还是两者都可以实现? 如果不能,我该如何做到另一个?

谢谢!

1个回答

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();
        }
    }
    
    现在您已经有了一个安全规则,需要通过注释来应用它:
  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中应启用安全注释:

  4. <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>
    

啊,谢谢你的快速回答,我没想到实现PermissionEvaluator会这么容易,看着AclPermissionEvaluator的实现,他们使用了某种ObjectIdentityRetrievalStrategy... - Pete
你可以同时拥有列表和代码高亮,只需添加四个额外的空格。我已经编辑了这篇文章作为示例,请查看源代码。 :) - Shadow The Spring Wizard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接