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

后端 未结 6 2039
说谎
说谎 2020-12-09 19:13

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

相关标签:
6条回答
  • 2020-12-09 19:47

    Use this code:

    if (springSecurityService.isLoggedIn()){   
            println "Logged In"
    
        }
    
    0 讨论(0)
  • 2020-12-09 19:57

    The following code is from the Spring Security Core Plugin (Version: 1.1.2) - Reference Documentation - Section 6.2

    grails.plugins.springsecurity.SpringSecurityService provides security utility functions. It is a regular Grails service, so you use dependency injection to inject it into a controller, service, taglib, and so on:

    class SomeController {
        def springSecurityService
        def someAction = { 
            def user = springSecurityService.currentUser 
            …
        } 
    }
    
    0 讨论(0)
  • 2020-12-09 20:02

    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()
         .....
         .....
      } 
    }
    
    0 讨论(0)
  • 2020-12-09 20:02

    Nowadays, I think the way to do it is:

    def user = getAuthenticatedUser()
    
    0 讨论(0)
  • 2020-12-09 20:08

    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.

    0 讨论(0)
  • 2020-12-09 20:12

    You can get current User by this way also

     class AnyController {
      def springSecurityService
      def someAction = { 
        def user = User.get(springSecurityService.principal.id)
    
         } 
     }
    
    0 讨论(0)
提交回复
热议问题