Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I would like to allow access to a particular method to more than one group of users. Is it possible in Spring Security 3.x to do such a thing using the @Secured annotation? Consider two groups (roles) OPERATOR and USER, would this code be valid:

     @Secured("ROLE_OPERATOR", "ROLE_USER")     public void doWork() {         // do useful processing     } 

like image 555
Paul Gregoire Avatar asked Oct 27 '11 15:10

Paul Gregoire


People also ask

What is usage of @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 is the difference between @secured and RolesAllowed?

@Secured and @RolesAllowed are the same the only difference is @RolesAllowed is a standard annotation (i.e. not only spring security) whereas @Secured is spring security only. @PreAuthorize is different in a way that it is more powerful then the other 2. It allows for SpEL expression for a more fine-grained control.

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

You're almost there. Syntactically, you need to write it like this:

@Secured({"ROLE_OPERATOR", "ROLE_USER"}) public void doWork() { ... } 

This is because you're supplying multiple values to a single array attribute of the annotation. (Java syntactically special-cases handing in a single value, but now you need to do it “properly”.)

like image 113
Donal Fellows Avatar answered Sep 20 '22 11:09

Donal Fellows


@Donal Fellows answer is correct for Spring apps. However, if you're working in Grails, you need to use the Groovy syntax for lists so the code would look like this

@Secured(["ROLE_OPERATOR", "ROLE_USER"]) public void doWork() { ... } 
like image 40
SGT Grumpy Pants Avatar answered Sep 18 '22 11:09

SGT Grumpy Pants