我正在开发一个应用程序,其中每个员工都有自己的客户。
当员工想要显示、修改或删除客户时,我想确保该客户是该员工之一。这是因为执行这些操作的 url 类似于
www.xxx.com/customers/update/{idCustomer}
我现在验证对客户的访问权限的方法是通过服务调用(具有数据库访问权限)来确保该客户是该员工之一。
该应用程序是使用 Spring MVC 和 Spring Security 编写的。我想知道是否有更好的方法来进行相同的限制访问?
最佳答案
我发现使用 hasPermission
可以方便地满足此类要求。具体来说,
- 通过使用
@EnableGlobalMethodSecurity(prePostEnabled = true) 注解配置类来启用方法安全性
- 在 Controller 中获取客户,然后调用服务方法,传递客户。
使用
@PreAuthorize注释服务方法
@PreAuthorize("hasPermission(#customer, 'edit')") public void updateCustomer(Customer customer, ...) { ...
您应该配置一个
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. } ... }
作为一种更简洁的模式,在上述方法中,您可以将权限检查委托(delegate)给实体类,如下所示:
BaseEntity baseEntity = (BaseEntity) entity; return entity.hasPermission(Util.getUser(auth), (String) permission);
参见this了解更多详情。
关于java - 限制某些数据访问的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31870844/