23

I am using the spring-security-core plugin in my grails app. I need to know the current user's role in a controller action. How can I retrieve that?

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
laxmi
  • 865
  • 6
  • 17
  • 27

6 Answers6

34

You can inject springSecurityService into your controller:

def springSecurityService

and then in your action, call:

def roles = springSecurityService.getPrincipal().getAuthorities()

See the docs here.

jonnybot
  • 2,435
  • 1
  • 32
  • 56
Mike Sickler
  • 33,662
  • 21
  • 64
  • 90
20

From a controller you can use two methods the plugin adds to the metaclass, getPrincipal and isLoggedIn:

def myAction = {
   if (loggedIn) {
      // will be a List of String
      def roleNames = principal.authorities*.authority
   }
}

If the action is secured you can skip the loggedIn/isLoggedIn() check.

Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
  • Cool, I didn't realize those were added to the metaclass. Are there any disadvantages to using, say, `authenticatedUser` in a controller over injecting the `springSecurityService` plugin? Looking at the plugin code, they seem mostly identical. – Rob Hruska Jun 24 '11 at 12:51
  • 1
    No difference, it's just more convenient. – Burt Beckwith Jun 24 '11 at 13:24
  • Can a user-specific variable (such as roleNames) be stored as a controller field? I suppose it is not safe to store any state in the controller, because it will be shared. Am I right? If so, is there any trick to avoid duplication of this code throughout all of the controller's actions? – Alex Fedulov Jul 31 '13 at 16:17
4

If you simply need to check to see if a user is in a specific role then use SpringSecurityUtils.ifAllGranted which takes a single String as an argument which contains a comma-delimited list of roles. It will return true if the current user belongs to all of them. SpringSecurityUtils also has methods like ifAnyGranted, ifNotGranted, etc, so it should work for whatever it is you are trying to accomplish.

matt forsythe
  • 3,863
  • 1
  • 19
  • 29
0

To get the user

    def springSecurityService
    def principal = springSecurityService.principal
    String username = principal.username
amit
  • 356
  • 3
  • 17
0

SecurityContextHolder knows that:

SecurityContextHolder.getContext().getAuthentication().getAuthorities()
Erik Kaju
  • 3,147
  • 3
  • 19
  • 28
-1

You can also use getAuthenticatedUser() by itself. This method is automatically injected in every controller, and thus only available from controllers. You will have to use one of the other methods if you want to access the current logged in user from anywhere else.

Pudpuduk
  • 1,549
  • 2
  • 14
  • 23