bryce
bryce

Reputation: 852

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}

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

Answers (1)

Sanjay
Sanjay

Reputation: 8955

I find using hasPermission convenient for such requirements. Specifically,

  1. Enable method security by annotating a configuration class with @EnableGlobalMethodSecurity(prePostEnabled = true)
  2. Fetch the customer in your controller, and call a service method, passing the customer.
  3. Annotate the service method with @PreAuthorize

    @PreAuthorize("hasPermission(#customer, 'edit')")
    public void updateCustomer(Customer customer, ...) {
    ...
    
  4. 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.
    }
    
    ...
    
    }
    
  5. 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

Related Questions