【问题标题】:How to store session Id's and associate them with user如何存储会话 ID 并将它们与用户关联
【发布时间】:2014-08-25 17:13:50
【问题描述】:

我有一个CustomSecurityEventListener 用于在成功验证后获取事件,CustomHttpSessionListener 用于设置最大非活动会话时间。

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 界面实现会话管理器,管理员可以在其中撤销属于给定用户的会话。

| userName1 | JSESSIONID1234 | action -> revoke |
| userName2 | JSESSIONID4321 | action -> revoke |

您是否知道如何使用自定义侦听器(使用 sessionCreated()sessionDestroyed() 方法)将 sessionId 与用户相关联,并将用户会话对存储在例如。 “活动会话”集合。

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

提前致谢。

【问题讨论】:

    标签: spring grails spring-security


    【解决方案1】:

    我在运行功能测试时使用以下侦听器代码来清理会话。

    不完全是您要查找的内容,但 getAllPrincipals() 显示了您如何从会话中获取用户(我使用 ':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
        }
    }
    

    【讨论】:

    • 谢谢。这就是我一直在寻找的。完美运行。
    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多