【问题标题】:Entity access based on owner user基于所有者用户的实体访问
【发布时间】:2013-07-11 00:25:43
【问题描述】:

我正在使用 Spring 安全性开发 Spring MVC webapp。

根据登录的用户和当前访问的实体,我必须允许或拒绝用户查看或修改它。如果用户创建了实体,他就是所有者,他可以处理实体。我可以验证它,因为 entity.user == user。

我也有这样的情况,用户只能通过获取实体的父级或 n-parent 来进行比较。例如 entity.nestedEntity.user == user

我已经看到 spring security 具有 ACL 支持(域对象安全),但我认为我无法处理“父场景”。而且我不是从一个空的数据库开始的。此外,我认为我需要为每个对象构建 acl。所以我认为这不是正确的方法。

现在我在控制器层进行检查,获取当前用户并将其与存储在请求对象中的用户进行比较。如果它们不相同,我会抛出 AccessDeniedException。

为了使事情尽可能简单,我可以采取哪些替代方法?

谢谢马尔科

【问题讨论】:

    标签: spring spring-mvc spring-security


    【解决方案1】:

    您可以实现自己的 PermissionEvaluator 来检查您的自定义权限逻辑。 然后你用 Spring Security 注册你新创建的 PermissionEvaluator ,你可以使用 您可以在 Spring Security 注释中检查您的自定义权限。

    最小示例(弹簧安全配置):

    <!-- Enable usage of @Pre & @Post security annotations -->
    <global-method-security secured-annotations="enabled"  pre-post-annotations="enabled">
          <expression-handler ref="expressionHandler"/>
    </global-method-security>
    
    <!-- Use CustomPermissionEvaluator as permission evaluator to control access to    application with specific permission rules -->
    <beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
         <beans:property name="permissionEvaluator" ref="customPermissionEvaluator"/>
    </beans:bean>
    
    <beans:bean id="customPermissionEvaluator" class="com.example.CustomPermissionEvaluator">
    

    然后您的 CustomPermissionEvalutor 应该具有 hasPermission 实现,该实现对您的自定义“OWNER”权限和您的自定义域对象进行权限检查。

    类似这样的:

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        ...
        if ("OWNER".equals(permission.toString()) && targetDomainObject instanceof Entity) {
             //fetch user from Authentication and verify if user is owner of Entity
        }
        ...
    }
    

    最后,您将能够使用注释来强制执行安全性:

    @PreAuthorize("hasPermission(#someEntity, 'OWNER')")
    public someMethod(Entity someEntity) { ... }
    

    也可以(但更复杂)添加可以在 Spring Security 注释中评估的新函数,在这种情况下,您可以添加自己的 isOwner 函数,PreAuthorize 可能看起来像 @PreAuthorize('isOwner(#someEntity)' ) 等等...

    【讨论】:

    • 嗯,我喜欢!我会试试看的!
    猜你喜欢
    • 2013-07-08
    • 2016-04-29
    • 2019-11-14
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    相关资源
    最近更新 更多