Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are multiple roles allowed in the @Secured annotation with 'or' condition in Spring Security

Tags:

I am using spring and spring security 4 in my project. I have to call my dao method with ROLE_USER or ROLE_TIMER_TASK.

Currently I am using this annotation -

 @Secured({"ROLE_USER", "ROLE_TIMER_TASK"})

This @Secured annotation allowing only those users who have both role but I wanna call this method by user who have any one role from this.

Could it be possible if user have any one role from this roles and call this method?

like image 973
Gourav Saklecha Avatar asked Apr 27 '16 14:04

Gourav Saklecha


People also ask

What is @secured annotation?

Using @Secured Annotation. The @Secured annotation is used to specify a list of roles on a method. So, a user only can access that method if she has at least one of the specified roles.

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

The difference between @Secured and @PreAuthorize are as follows : The main difference between @Secured and @PreAuthorize is that @PreAuthorize can work with Spring EL. We can access methods and properties of SecurityExpressionRoot while using @PreAuthorize but not with @Secured.


2 Answers

For or, use a @PreAuthorize annotation instead:

@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_TIMER_TASK')")

In Spring Security version 4 the ROLE_ prefix can be omitted:

@PreAuthorize("hasRole('USER') or hasRole('TIMER_TASK')")

Make sure you have pre- and post-annotations enabled in your security config.

like image 134
holmis83 Avatar answered Sep 23 '22 14:09

holmis83


To call the method by any of the role mentioned use:

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

and enable pre- and post- annotations in security Class :

@EnableGlobalMethodSecurity(prePostEnabled = true)
like image 31
Anubhav Jain Avatar answered Sep 22 '22 14:09

Anubhav Jain