Multiple roles using @PreAuthorize
Asked Answered
S

5

25

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?

Seleucid answered 29/7, 2019 at 5:30 Comment(0)
B
31

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

Baton answered 29/7, 2019 at 11:1 Comment(0)
R
36

@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/

Resurrection answered 23/10, 2020 at 7:30 Comment(1)
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.Hema
B
31

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

Baton answered 29/7, 2019 at 11:1 Comment(0)
B
14

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

@PreAuthorize("hasRole('" + AuthoritiesConstants.USER + "')" +
              " && hasRole('" + AuthoritiesConstants.ADMIN + "')" )
Bifoliolate answered 29/7, 2019 at 5:52 Comment(2)
How can we implement CustomPermissionEvaluator in jhipster?Seleucid
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 answeredBifoliolate
Z
2

SecurityExpressionOperations interface in package org.springframework.security.access.expression; contains all the authorization-related methods.

Below are the most useful methods for authentication.

boolean hasRole(String role);
boolean hasAnyRole(String... roles)
boolean isAuthenticated();
boolean hasPermission(Object target, Object permission);
boolean hasPermission(Object targetId, String targetType, Object permission);
Zeralda answered 11/12, 2022 at 11:18 Comment(0)
F
0

I believe the best option is to use @PreAuthorize("hasAnyRole()")

In this case I suppose @PreAuthorize("hasAnyRole(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)")

Frutescent answered 24/8, 2022 at 19:35 Comment(1)
hasAnyRole is not a method, you can't just pass AuthoritiesConstants.USER there, because than it will try to match with exact String like "AuthoritiesConstants.USER" instead of a USER field value of AuthoritiesConstants classMaurilia

© 2022 - 2024 — McMap. All rights reserved.