spring - 如何存储 session ID并将其与用户相关联

标签 spring grails spring-security

我有一个CustomSecurityEventListener可以在成功通过身份验证后获取事件,还有CustomHttpSessionListener可以设置最大非 Activity session 时间。

class CustomSecurityEventListener implements ApplicationListener<AbstractAuthenticationEvent>, LogoutHandler {

    def grailsApplication
    def sessionRegistry

    @Transactional
    void onApplicationEvent(AbstractAuthenticationEvent event) throws AuthenticationException {
        if(event instanceof AuthenticationSuccessEvent){
            // user auditing actions

        }
}

我想用Web界面实现 session 管理器,管理员可以撤消属于给定用户的 session 。
| userName1 | JSESSIONID1234 | action -> revoke |
| userName2 | JSESSIONID4321 | action -> revoke |

您是否有任何想法如何使用自定义侦听器(使用sessionCreated()sessionDestroyed()方法)将sessionId与用户相关联,并将用户 session 对存储在中。 “activeSession”集合。

我不想将sessionId作为属性存储在Spring Security User类中。

提前致谢。

最佳答案

运行功能测试时,我正在使用以下侦听器代码清理 session 。

不完全是您要查找的内容,但getAllPrincipals()显示了如何从 session 中吸引用户(我使用':spring-security-core:1.2.7.3'创建了该代码)。

import static org.springframework.security.web.context.HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY

class SessionListener implements HttpSessionListener {
    def sessions = [:].asSynchronized()

    void sessionCreated (HttpSessionEvent se) {
        sessions.put(se.session.id, se.session)
    }

    void sessionDestroyed (HttpSessionEvent se) {
        sessions.remove(se.session.id)
    }

    void invalidateSessions () {
        def httpSessions = sessions.collect {String sessionId, HttpSession session ->
            session
        }

        httpSessions.each { HttpSession session ->
            session.invalidate()
        }
    }

    def getAllPrincipals () {
        def principals = []
        sessions.each { String sessionId, HttpSession session ->
            SecurityContext securityContext = session[SPRING_SECURITY_CONTEXT_KEY]
            def authentication = securityContext?.authentication
            principals << authentication?.principal
        }
        principals = principals.findAll {it != null}
        principals
    }
}

关于spring - 如何存储 session ID并将其与用户相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24573024/

相关文章:

java - 为什么 @Autowired 在我的 Controller 中工作但在我的服务中不起作用?

java - 如何在 SpEL 中引用 ApplicationEventPublisher?

database - 如何访问数据库 API 以获取记录

rest - 在 Grails 中持续轮询 REST 服务

java - Thymeleaf 上下文 URL 处理 - 如何将语言代码添加到上下文相关 URL (Spring + Thymeleaf)

hibernate - Grails/GORM,禁用一级缓存

java - 如何将身份验证从 LDAP 更改为 JDBC 以保护我的应用程序

java - 如何调试spring依赖顺序?

security - Spring 安全性 - SecurityContext.authentication 在 taglib 和 jsp 中为 null,但在 Controller 中还可以

java - 在 Postgres 数据库中使用 ArrayList 成员保存 POJO