【问题标题】:How to expire previous session on a concurrent session access如何在并发会话访问中使上一个会话过期
【发布时间】:2017-03-27 15:02:32
【问题描述】:

我在我的 grails 应用程序中使用了 Spring Security。在不同的浏览器上使用相同的用户名登录时,我需要使上一个会话过期。并发会话限制会对此有所帮助吗?如何做到这一点?

【问题讨论】:

    标签: spring grails


    【解决方案1】:

    我需要在使用相同的登录时使上一个会话过期 其他浏览器上的用户名。并发会话限制是否会 帮忙?

    是的,在这方面,并发会话最适合您。

    如何做到这一点?

    创建您自己的类(在 /src/groovy/ 下)通过扩展 ConcurrentSessionControlStrategy 类来处理并发会话,如下所示

    import com.constants.CodeConstants
    import org.springframework.security.core.session.SessionRegistry
    import org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy
    
    /**
     * Overrides the default "ConcurrentSessionControlStrategy"
     * for limiting the maximum allowed session per user role
     */
    class MyConcurrentSessionControlStrategy extends ConcurrentSessionControlStrategy{
    
        MyConcurrentSessionControlStrategy(SessionRegistry sessionRegistry) {
            super(sessionRegistry)
        }
    
        /**
         * Check if role is "ROLE_SUPER_ADMIN" then set allowed session to 1
         * else unlimited (i.e. -1)
         *
         * @param authentication
         *
         * @return : maximum allowed sessions
         */
        protected int getMaximumSessionsForThisUser(org.springframework.security.core.Authentication authentication) {
    
            Long maximumSession = -1
    
            if (CodeConstants.ROLE_SUPER_ADMIN in authentication.authorities*.authority) {
                maximumSession = 1
            }
    
            return maximumSession;
        }
    }
    

    在我的情况下,我将超级管理员用户限制为只有一个会话,您可以拥有多个角色用户。

    并在resources.groovy 下注册我们的实现bean,如下所示

    import com.security.MyConcurrentSessionControlStrategy
    import org.springframework.security.core.session.SessionRegistryImpl
    import org.springframework.security.web.session.ConcurrentSessionFilter
    
       /**
         * For handling the concurrent session control
         * exceptionIfMaximumExceeded = false -> invalidates the previous session
         * exceptionIfMaximumExceeded = true -> invalidates the new session
         */
        sessionRegistry(SessionRegistryImpl)
    
        concurrencyFilter(ConcurrentSessionFilter) {
            sessionRegistry = sessionRegistry
            logoutHandlers = [ref("rememberMeServices"), ref("securityContextLogoutHandler")]
            expiredUrl = '/login/auth'
        }
    
        concurrentSessionControlStrategy(MyConcurrentSessionControlStrategy, sessionRegistry) {
            alwaysCreateSession = true
            exceptionIfMaximumExceeded = false
            maximumSessions = -1
        }
    

    注意:上面的代码已经过测试并按预期工作 Grails version 2.4.4 和弹簧安全 spring-security-core:2.0.0插件

    【讨论】:

    • 这个答案很有帮助。非常感谢 Prakash Thete
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 2010-09-25
    • 1970-01-01
    • 2013-05-25
    • 2013-03-31
    相关资源
    最近更新 更多