如何使并发会话访问的前一个会话到期

时间:2017-03-27 05:38:27

标签: spring grails

我在grails应用程序中使用spring security。我需要在其他浏览器上使用相同的用户名登录时使之前的会话失效。并发会话限制是否有助于此?怎么做?

1 个答案:

答案 0 :(得分:2)

  

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

是的,在这方面,并发会议对你来说是最好的。

  

怎么做?

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

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插件