Grails和Spring安全性:如何从控制器中获取经过身份验证的用户?

Grails和Spring安全性:如何从控制器中获取经过身份验证的用户?,grails,Grails,我最近从JSecurity插件转到了SpringSecurity。如何从控制器中获取经过身份验证的用户?我使用的是0.5.1,以下内容适用于我: class EventController { def authenticateService def list = { def user = authenticateService.principal() def username = user?.getUsername() ..... .....

我最近从JSecurity插件转到了SpringSecurity。如何从控制器中获取经过身份验证的用户?

我使用的是0.5.1,以下内容适用于我:

class EventController {
  def authenticateService

  def list = { 
     def user = authenticateService.principal() 
     def username = user?.getUsername()
     .....
     .....
  } 
}

它目前没有文档记录,但在插件安装文件中,它向每个控制器添加了3种方法,因此您实际上不必注入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'
    }
}
这意味着你可以直接打电话

principalInfo

获取主对象。它还具有“isUserLogin”以查看用户是否已登录,以及“authUserDomain”以获取与登录用户主体关联的实际域类实例(个人/用户)。

以下代码来自

grails.plugins.springsecurity.SpringSecurityService提供安全实用程序功能。它是一个常规的Grails服务,因此您可以使用依赖项注入将其注入控制器、服务、标记库等:

class SomeController {
    def springSecurityService
    def someAction = { 
        def user = springSecurityService.currentUser 
        …
    } 
}

现在,我认为这样做的方法是:

def user = getAuthenticatedUser()

您也可以通过这种方式获取当前用户

 class AnyController {
  def springSecurityService
  def someAction = { 
    def user = User.get(springSecurityService.principal.id)

     } 
 }
使用此代码:

if (springSecurityService.isLoggedIn()){   
        println "Logged In"

    }

太好了-谢谢!只是上面代码中的一个输入错误。它应该是def username=user?.getUsername()。请注意,新版本的Spring Security进行了一些更改。另外请注意,如果您使用服务,那么初始化不应该在方法体中进行,而应该在类中进行。我花了一个半小时的时间用头敲击键盘,试图让Acegi plug使用中所示的文件上载模式,直到我发现了这一点。谢谢现在getPrincipalInfo方法被称为getAuthenticateduser,但是感谢您提供的好提示@lucke84看起来你是对的:-在这个插件的现代版本中,所有的方法似乎都改变了名称