11

To check multiple roles has the method level access

I have used @PreAuthorize annotation to check the role

@PreAuthorize("hasRole(\"" + AuthoritiesConstants.USER + "\",)" )

How to check multiple roles using @PreAuthorize annotaion?

Gaël Marziou
  • 15,258
  • 4
  • 38
  • 47
P Rajesh
  • 226
  • 1
  • 2
  • 11

3 Answers3

22

You can create a custom annotation to validate many roles and conditions. P.e.:

@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_AGENT) " +
        "|| hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_ADMIN)" +
        "|| (hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_CUSTOMER) && #userId == principal.username)")
public @interface IsAuthenticatedAsAgentOrCustomerIsUserId {
}

Then, you can use this annotation as below:

@IsAuthenticatedAsAgentOrCustomerIsUserId
Folder findByUserIdAndType(@Param("userId") String userId, @Param("typeId") FolderType id);

This annotation validate that user logged as role AGENT or ADMIN. If user has role CUSTOMER validate if userId parameter is equals to user logged

13

@PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")

hasAnyRole() 

When you need to support multiple roles, you can use the hasAnyRole() expression.

@PreAuthorize("hasAnyRole('ADMIN','DB-ADMIN')")

https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html https://www.appsdeveloperblog.com/spring-security-preauthorize-annotation-example/

Rohit.007
  • 3,324
  • 2
  • 18
  • 29
Oleh Tatsiun
  • 381
  • 2
  • 5
  • 2
    While this code may answer the question, it is better to include any piece of reference, advice and guidelines here. Code-only answers give a solution but not really an answer. – Cyril CHAPON Oct 23 '20 at 08:21
10

Simply combine roles by using && or || in SpEL expressions

@PreAuthorize("hasRole('" + AuthoritiesConstants.USER + "')" +
              " && hasRole('" + AuthoritiesConstants.ADMIN + "')" )
Nikolai Shevchenko
  • 5,919
  • 8
  • 34
  • 35
  • How can we implement CustomPermissionEvaluator in jhipster? – P Rajesh Jul 29 '19 at 09:38
  • 1
    That's a broad question. Since JHipster is based on Spring you should refer to Spring Security tutorial for details. Or search here at StackOverflow, it might be already answered – Nikolai Shevchenko Jul 29 '19 at 10:06