Sunday, May 1, 2011

Grails and Spring Security: How do I get the authenticated user from within a controller?

I recently moved from the JSecurity plugin to Spring Security. How do I get the authenticated user from within my controllers?

From stackoverflow
  • I'm using 0.5.1 and the following works for me:

    class EventController {
      def authenticateService
    
      def list = { 
         def user = authenticateService.principal() 
         def username = user?.getUsername()
         .....
         .....
      } 
    }
    
    Mike Sickler : Great- thanks! Just a typo in your above code. It should be def username = user?.getUsername()
    John Wagenleitner : Thanks for catching that, I corrected it.
  • It's not currently documented, but in the plugin installation file, there are 3 methods that it adds to every controller so that you don't actually have to inject the authenticationService:

    private void addControllerMethods(MetaClass mc) {
     mc.getAuthUserDomain = {
      def principal = SCH.context?.authentication?.principal
      if (principal != null && principal != 'anonymousUser') {
       return principal?.domainClass
      }
    
      return null
     }
    
     mc.getPrincipalInfo = {
      return SCH.context?.authentication?.principal
     }
    
     mc.isUserLogon = {
      def principal = SCH.context?.authentication?.principal
      return principal != null && principal != 'anonymousUser'
     }
    }
    

    This means that you can just call

    principalInfo
    

    To get the principal object. It also has "isUserLogin" to see if the user is logged and "authUserDomain" to get the actual domain class instance (the Person/User) associated with the principal of the logged in user.

    John Wagenleitner : Great info, thanks for the tip.
    Visionary Software Solutions : I spent an hour and a half banging my head against the keyboard trying to get Acegi plug to work with the File Upload pattern shown in http://www.packtpub.com/article/file-sharing-in-grails until I found this. Thanks!

0 comments:

Post a Comment