限制某些数据访问的正确方法是什么 [英] What is the proper way to restrict the access of some data
问题描述
我正在开发一个应用程序,其中每个员工都有自己的客户.
当员工想要显示,修改或删除客户时,我要确保此客户是该员工之一.那是因为执行这些操作的网址就像
I'm working on an application where each employee have there own customers.
When an employee wants to display, modifiy or delete a customer, I want to ensure that this customer is one of this employee. That's because of the url to do those actions are like
www.xxx.com/customers/update/{idCustomer}
我目前对客户的访问权限有效的方法是通过服务调用(具有数据库访问权限)来确保此客户是该员工之一.
该应用程序是使用带有Spring Security的Spring MVC编写的.我想知道是否有更好的方法可以进行相同的限制访问?
The way I valid the access to the customer for now is with a service call (with database access) to ensure this customer is one of this employee.
This application is written in Spring MVC with Spring Security. I would like to know if there is a better way to do the same restriction access?
推荐答案
我发现使用hasPermission
可以满足此类要求.具体来说,
I find using hasPermission
convenient for such requirements. Specifically,
- 通过用
@EnableGlobalMethodSecurity(prePostEnabled = true)
注释配置类来启用方法安全性
- 在控制器中获取客户,并调用服务方法来传递客户.
-
用
@PreAuthorize
- Enable method security by annotating a configuration class with
@EnableGlobalMethodSecurity(prePostEnabled = true)
- Fetch the customer in your controller, and call a service method, passing the customer.
Annotate the service method with
@PreAuthorize
@PreAuthorize("hasPermission(#customer, 'edit')")
public void updateCustomer(Customer customer, ...) {
...
您应该已经配置了PermissionEvaluator
,如下所示:
You should have configured a PermissionEvaluator
, like this:
@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.
}
...
}
作为一种更简洁的模式,在上述方法中,您可以将权限检查委托给实体类,如下所示:
As a cleaner pattern, in the above method, you can delegate the permission checks to the entity classes, like this:
BaseEntity baseEntity = (BaseEntity) entity;
return entity.hasPermission(Util.getUser(auth), (String) permission);
请参见此了解更多信息.
这篇关于限制某些数据访问的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!