Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom method within spring @Preauthorize

I am implementing an application which has some methods to which's access will be fully based on permissions. The permissions are implemented using Spring. The permissions are added using @PreAuthorize annotation on top of the methods. The problem is that I would like to have fully custom methods (EL) within the annotations. So what I would like to achieve is for instance:

@PreAuthorize("customAllowThis()")
public void foo() { }

I think there are two approaches:

Approach 1: Try to override SecurityExpressionRoot and add my custom methods there. I will use multiple authorisation services on different methods, so putting all specific methods to SecurityExpressionRoot would be a big chaos.

Approach 2: Create service and place the method there:

@Component
public class AuthorisationService {
    public boolean allowThis() {
         return true;
    }
}

and do something like:

@PreAuthorize("@authorisationService.customAllowThis()")
public void foo() { }

I much more prefer Approach 2 although it looks for me like it would bypass the "natural order" of Spring. Are there any good/best practices in terms of how to handle such situation? The point is that I wouldn't like to stick all specific methods into one class but from the other hand I wouldn't like to do something "dirty".

like image 754
Taks Avatar asked Oct 31 '22 20:10

Taks


1 Answers

To achieve this, you can do the following :

  1. Create a custom annotation that accepts an array of allowed roles, something like this :

    @Allows({RoleEnum.ROLE1, RoleEnum.ROLE2 })

  2. using SPeL, we can invoke a custom method that will check if the user has these Roles, something like this :

    @PreAuthorize("myServiceClass.hasRoles(#roles)")

  3. in the service class, you can just validate the user roles against the roles from OAuth database, and perform any business logic in the service.

like image 144
Manik Jain Avatar answered Nov 12 '22 10:11

Manik Jain