Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple roles using @PreAuthorize

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?

like image 338
P Rajesh Avatar asked Jul 29 '19 05:07

P Rajesh


People also ask

What is the use of @PreAuthorize annotation?

The @PreAuthorize annotation checks the given expression before entering the method, whereas the @PostAuthorize annotation verifies it after the execution of the method and could alter the result.

What's the difference between @secured and @PreAuthorize in Spring Security?

The real difference is that @PreAuthorize can work with Spring Expression Language (SpEL). You can: Access methods and properties of SecurityExpressionRoot . (Advanced feature) Add your own methods (override MethodSecurityExpressionHandler and set it as <global-method-security><expression-handler ... /></...> ).

What is @PreAuthorize annotation in spring boot?

Method-level security is implemented by placing the @PreAuthorize annotation on controller methods (actually one of a set of annotations available, but the most commonly used). This annotation contains a Spring Expression Language (SpEL) snippet that is assessed to determine if the request should be authenticated.

What is @secured annotation?

The Secured annotation is used to define a list of security configuration attributes for business methods. This annotation can be used as a Java 5 alternative to XML configuration.


1 Answers

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

like image 179
Oleh Tatsiun Avatar answered Sep 19 '22 18:09

Oleh Tatsiun