代码之家  ›  专栏  ›  技术社区  ›  Simon

如何使用acegi将登录用户的ID传递给grails中选择的控制器

  •  0
  • Simon  · 技术社区  · 16 年前

    我已经使用Acegi插件保护了我的Grails应用程序,并且正在使用控制器方法上的注释来提示用户登录。

    我的应用程序有一个静态的HTML首页,上面有一个登录链接,可重定向到 login/auth 页。成功登录后,我希望为经过身份验证的用户加载自己的自定义页面,调用 person/mainpage .

    在我的 LoginController 有以下代码…

    def index = {
        if (isLoggedIn()) {
            redirect uri: '/'
        }
        else {
            redirect action: auth, params: params
        }
    }
    
    /**
     * Show the login page.
     */
    def auth = {
    
        nocache response
    
        if (isLoggedIn()) {
            redirect uri: '/'
            return
        }
    
        String view
        String postUrl
        def config = authenticateService.securityConfig.security
        if (config.useOpenId) {
            view = 'openIdAuth'
            postUrl = "${request.contextPath}/login/openIdAuthenticate"
        }
        else if (config.useFacebook) {
            view = 'facebookAuth'
            postUrl = "${request.contextPath}${config.facebook.filterProcessesUrl}"
        }
        else {
            view = 'auth'
            postUrl = "${request.contextPath}${config.filterProcessesUrl}"
        }
    
        render view: view, model: [postUrl: postUrl]
    }
    

    这会将成功的登录重定向回应用程序的主页(/),这不是我想要的。搜索一会儿,我发现我可以在 securityconfig.groovy 这样地。。

    defaultTargetUrl = "/person/mainpage"
    

    我的问题是如何确定当我登录到我的 mainpage 我的行动 PersonController ?

    起初,我在LoginController中更改了索引操作,以像这样重定向到我的页面…

    def index = {
        if (isLoggedIn()) {
            redirect controller: person, action: mainpage, params: params 
        }
        else {
            redirect action: auth, params: params
        }
    }
    

    但登录人员的ID不会显示在 params (我觉得我很高兴,因为仅仅通过将用户行ID定义为URL参数就可以调出页面似乎很疯狂)。

    那么,正确的方法是什么呢?基本上我想要我的 人/主页 能够解析当前登录用户的操作。

    1 回复  |  直到 16 年前
        1
  •  2
  •   Burt Beckwith    16 年前

    您可以使用authenticateservice访问登录的用户。要获取用户/个人域实例,请调用authenticateservice.user domain()并仅获取身份验证(其getUsername()方法可能足够),请调用authenticateservice.principal()。如果您的默认targeturl是“/person/mainpage”,那么您的PersonController的“mainpage”操作将如下所示:

    class PersonController {
    
       def authenticateService
    
       def mainpage = {
          def user = authenticateService.userDomain()
          if (user) {
             log.info "you're logged in as $user.username"
          }
          else {
             log.info "you're not logged in"
          }
          [user: user]
       }
    }
    

    然后在mainpage.gsp中提供“用户”来呈现数据。

    推荐文章