Sankalp
Sankalp

Reputation: 2086

How can I annotate a method with Spring Security so that a caller is required to have one of a list of roles?

I am using Java annotations to grant permissions to a particular method. So far I have not found a way to make my method accessible to multiple roles. Single role works fine with @Secured("ROLE_CUSTOMER"). Is there a way to do hasRole('role1','role2')?

Upvotes: 18

Views: 21458

Answers (4)

Sankalp
Sankalp

Reputation: 2086

Found an exact solution to the problem:

@PreAuthorize("hasAnyRole('ROLE_CUSTOMER','ROLE_OFFICEADMIN','ROLE_EMPLOYEE')") 

Upvotes: 43

PaulMurrayCbr
PaulMurrayCbr

Reputation: 1260

The grails "Secured" annotation is different form the spring "Secured" annotation. Grails takes an array of strings. Spring takes a weird security expression language.

so:

import org.springframework.security.access.annotation.Secured;
@Secured('hasAnyRole([\'FOO-ROLE\'])')

or:

import grails.plugins.springsecurity.Secured;
@Secured(['FOO-ROLE'])

Upvotes: -2

Cristiano Fontes
Cristiano Fontes

Reputation: 5088

To make that happen I often use this

import this into your JSP

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

and know you can use this to handle security like in if taglib

<sec:authorize access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"/>

There is also another one like this to not permit those... i think it's HasNoRole

Anyway this works !

Upvotes: 7

Simone
Simone

Reputation: 2311

Just:

@Secured({"ROLE1", "ROLE2", "ROLE3"})

Upvotes: 11

Related Questions