【问题标题】:What is the proper way to restrict the access of some data限制某些数据访问的正确方法是什么
【发布时间】:2015-08-07 16:55:11
【问题描述】:

我正在开发一个应用程序,其中每个员工都有自己的客户。

当员工想要显示、修改或删除客户时,我想确保该客户是该员工之一。那是因为执行这些操作的 url 就像

www.xxx.com/customers/update/{idCustomer}

我现在验证客户访问权限的方式是通过服务调用(具有数据库访问权限)来确保该客户是该员工之一。

这个应用程序是用 Spring MVC 和 Spring Security 编写的。我想知道是否有更好的方法来做同样的限制访问?

【问题讨论】:

  • 这对于一个 SO 问题来说相当广泛......看起来 Spring 对您的问题的安全性答案是使用 ACL 和 ACE 的域对象安全性。您将域对象置于与在体面的文件系统中的文件上几乎相同的授权级别,并使用方法注释来控制它们。它可能不是 Spring Security 中最简单的部分,但却非常强大。
  • 您可以在客户表中添加员工外键。因此,您可以控制客户是否属于某个员工。这可能是解决您的问题的更简单方法

标签: java spring spring-mvc spring-security


【解决方案1】:

我发现使用hasPermission 很方便满足此类要求。具体来说,

  1. 通过使用@EnableGlobalMethodSecurity(prePostEnabled = true) 注释配置类来启用方法安全性
  2. 在控制器中获取客户,并调用服务方法,传递客户。
  3. @PreAuthorize注解服务方法

    @PreAuthorize("hasPermission(#customer, 'edit')")
    public void updateCustomer(Customer customer, ...) {
    ...
    
  4. 你应该已经配置了PermissionEvaluator,像这样:

    @Component
    public class PermissionEvaluatorImpl implements PermissionEvaluator {
    
    @Override
    public boolean hasPermission(Authentication auth,
        Object entity, Object permission) {
    
            // return true only if auth has the given
            // permission for the customer.
            // Current user can be obtained from auth.
    }
    
    ...
    
    }
    
  5. 作为一种更简洁的模式,在上述方法中,您可以将权限检查委托给实体类,如下所示:

    BaseEntity baseEntity = (BaseEntity) entity;
    return entity.hasPermission(Util.getUser(auth), (String) permission);
    

更多详情请见this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2011-02-04
    • 2011-09-14
    相关资源
    最近更新 更多