Gourav Saklecha
Gourav Saklecha

Reputation: 363

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

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?

Upvotes: 22

Views: 24912

Answers (3)

holmis83
holmis83

Reputation: 16604

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.

Upvotes: 42

Anubhav Jain
Anubhav Jain

Reputation: 71

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)

Upvotes: 7

Joe Grandja
Joe Grandja

Reputation: 678

In addition to the previous answer by holmis83....

To enable pre- and post- annnotations for method security:

Java Config:

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig {
// ...
}

Xml Config:

<global-method-security pre-post-annotations="enabled"/>

Upvotes: 3

Related Questions