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 }
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.
@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.
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.
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”.)
@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() { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With