无法在 Spring Security 登录事件侦听器中获取“记住我”用户的会话 ID

Posted

技术标签:

【中文标题】无法在 Spring Security 登录事件侦听器中获取“记住我”用户的会话 ID【英文标题】:Cannot get session ID for "remember me" users inside spring security login event listener 【发布时间】:2011-05-31 18:02:20 【问题描述】:

我正在使用 grails 和 spring-security 3.0.3 编写一个 Web 应用程序,它要求我保留所有成功登录的数据库记录,包括用户名、时间、ip 和 sessionId。

我已经创建了一个登录监听器(groovy 代码):

class DpLoginListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> 
    void onApplicationEvent(InteractiveAuthenticationSuccessEvent event) 
        def source = event.getSource()
        def principal = source.principal
        def details = source.details
        TrafficLogin.withTransaction 
            new TrafficLogin(userId: principal.id, ipAddress: details.remoteAddress, sessionId: details.sessionId ?: 'remember me').save(failOnError: true)
        
    

这会在用户登录时按预期触发,但当有人以“记住我”用户的身份返回站点时,sessionId 为空。这是预期的行为吗?登录成功时不应该创建会话吗?

我尝试通过添加一个单独的 SessionCreationEvent 侦听器来解决此问题,该侦听器将为用户找到最新的数据库登录记录,并在会话存在后立即使用正确的 sessionId 更新该行,但似乎此会话创建事件永远不会火灾,我不知道为什么。

会话创建监听器如下所示:

class DpSessionCreatedListener implements ApplicationListener<SessionCreationEvent> 
  void onApplicationEvent(SessionCreationEvent event) 
    def source = event.getSource()
    def principal = source.principal
    def details = source.details
    TrafficLogin.withTransaction 
      def rememberMe = TrafficLogin.find("from TrafficLogin as t where t.userId=? and t.sessionId='remember me' order by t.dateCreated desc", principal.id)
      if (rememberMe) 
        rememberMe.sessionId = details.sessionId
        rememberMe.save(failOnError:true)
      
    
  

并且在我的 resources.groovy 文件中为它定义了一个 bean,其方式与登录侦听器相同,可以正常触发。

知道如何正确设置这个 sessionId 吗?

【问题讨论】:

【参考方案1】:

与 grails 无关,但如果 grails 支持,此 SO question 可能会提供解决方法。

【讨论】:

以上是关于无法在 Spring Security 登录事件侦听器中获取“记住我”用户的会话 ID的主要内容,如果未能解决你的问题,请参考以下文章

无法登录 Spring Security

Grails Spring Security Core无法登录

我无法使用 Spring Security 登录

Grails + Spring Security:无法登录

由于重定向循环,Grails Spring Security 无法显示登录页面

无法在 Spring Security 中用自定义替换标准登录表单