限制某些数据访问的正确方法是什么
问题内容:
我正在开发一个应用程序,其中每个员工都有自己的客户。
当员工想要显示,修改或删除客户时,我要确保此客户是该员工之一。那是因为执行这些操作的网址就像
www.xxx.com/customers/update/{idCustomer}
我目前对客户的访问权限有效的方法是通过服务调用(具有数据库访问权限)来确保此客户是该员工之一。
该应用程序是使用带有Spring Security的Spring MVC编写的。我想知道是否有更好的方法来进行相同的限制访问?
问题答案:
我发现使用hasPermission
这种要求很方便。特别,
- 通过注释配置类来启用方法安全性
@EnableGlobalMethodSecurity(prePostEnabled = true)
- 在控制器中获取客户,然后调用服务方法来传递客户。
-
注释服务方法
@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.
}
…
}
-
作为一种更简洁的模式,在上述方法中,您可以将权限检查委托给实体类,如下所示:
BaseEntity baseEntity = (BaseEntity) entity;
return entity.hasPermission(Util.getUser(auth), (String) permission);
请参阅此了解更多详情。