限制某些数据访问的正确方法是什么

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

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

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

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

此应用程序是使用Spring Security在Spring MVC中编写的。 我想知道是否有更好的方法来进行相同的限制访问?

我发现使用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); 

有关详细信息,请参阅此