Benjamin Muschko
Benjamin Muschko

Reputation: 33426

Access/check Spring Security hierarchical roles programmatically

In my Grails project I defined multiple hierarchical roles using the Spring Security plugin e.g. ROLE_USER > SOME_OTHER_ROLE. When securing controller methods using the @Secured annotation it works just fine. However, I also would like to check the role programmatically in my code for one use case. Using the following approach I always get a false even though the user inherits the role through hierarchical role definition:

request.isUserInRole('SOME_OTHER_ROLE')

Also the following calls never directly return the inherited roles:

SecurityContextHolder.context?.authentication?.authorities
springSecurityService.getPrincipal().getAuthorities()

Is there a way of checking if the user also has the inherited role?

Upvotes: 2

Views: 1366

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75671

This seems like a bug (or at least an omission) in SecurityContextHolderAwareRequestWrapper which adds a request wrapper to implement the isUserInRole method.

You can use the roleVoter bean's extractAuthorities method. Add a dependency injection for it (def roleVoter) and then call

def allRoles = roleVoter.extractAuthorities(
        SecurityContextHolder.context.authentication)

Upvotes: 2

Related Questions