Search code examples
springgrailsspring-securityspring-el

Does Spring Security have a 'hasAllRole' that performs the AND version of 'hasAnyRole'


I'm using Spring Security in Grails to restrict access to my controllers. I have a use case where I want to check that a user has multiple roles assigned. I realize I could just make another role that is synonymous with 'person has these two roles', but it would require much more changes than I'd like.

Spring Security has an OR version expression to check if a user has any of a list of roles:

//allow user to access if he has role ROLE_ADMIN -OR- ROLE_USER
//note this is shortcut notation for hasAnyRole(["ROLE_ADMIN","ROLE_USER"])
@Secured(["ROLE_ADMIN","ROLE_USER"])
def index = {}

Is there a method, or just way using Spring Expression Language (SpEL) to do the following:

//allow user to access if he has role ROLE_ADMIN -AND- ROLE_USER
@Secured("hasAllRole(['ROLE_ADMIN','ROLE_USER']")
def index = {}

Note: SpringSecurityUtils class does have the method

public static boolean ifAllGranted(final String roles)

Solution

  • If you use @PreFilter instead of @Secured then you can write:

    @PreFilter("hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')")