Reputation: 852
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}
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?
Upvotes: 2
Views: 3938
Reputation: 8955
I find using hasPermission
convenient for such requirements. Specifically,
@EnableGlobalMethodSecurity(prePostEnabled = true)
Annotate the service method with @PreAuthorize
@PreAuthorize("hasPermission(#customer, 'edit')")
public void updateCustomer(Customer customer, ...) {
...
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);
See this for more details.
Upvotes: 3