代码之家  ›  专栏  ›  技术社区  ›  Mike Sickler

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

  •  12
  • Mike Sickler  · 技术社区  · 16 年前

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

    6 回复  |  直到 16 年前
        1
  •  10
  •   John Wagenleitner    16 年前

    我使用的是0.5.1,以下功能适用于我:

    class EventController {
      def authenticateService
    
      def list = { 
         def user = authenticateService.principal() 
         def username = user?.getUsername()
         .....
         .....
      } 
    }
    
        2
  •  15
  •   Ted Naleid    16 年前

    目前还没有文档记录,但是在插件安装文件中,有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”来获取与已登录用户主体关联的实际域类实例(个人/用户)。

        3
  •  13
  •   Chris    14 年前

    以下代码来自 Spring Security Core Plugin (Version: 1.1.2) - Reference Documentation - Section 6.2

    grails.plugins.springsecurity.springsecurityservice提供安全实用程序功能。它是一个常规的Grails服务,因此使用依赖注入将其注入到控制器、服务、Taglib等中:

    class SomeController {
        def springSecurityService
        def someAction = { 
            def user = springSecurityService.currentUser 
            …
        } 
    }
    
        4
  •  5
  •   chelder    12 年前

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

    def user = getAuthenticatedUser()
    
        5
  •  2
  •   Free-Minded    12 年前

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

     class AnyController {
      def springSecurityService
      def someAction = { 
        def user = User.get(springSecurityService.principal.id)
    
         } 
     }
    
        6
  •  0
  •   Bo Persson Touseef    9 年前

    使用此代码:

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