gpt4 book ai didi

spring - 如何在并发 session 访问中使上一个 session 到期

转载 作者:行者123 更新时间:2023-12-02 14:29:39 30 4
gpt4 key购买 nike

我在grails应用程序中使用spring安全性。在其他浏览器上使用相同的用户名登录时,我需要使上一个 session 到期。并发 session 限制是否有帮助?这该怎么做?

最佳答案

I need to expire the previous session while login with the same username on a different browser. Does concurrent session limiting will help this?



是的,在这方面,并发 session 将是您的最佳选择。

How to do this ?



通过扩展 ConcurrentSessionControlStrategy类,如下创建您自己的类(在/ src / groovy /下)以处理并发 session
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;
}
}

就我而言,我仅将 super 管理员用户限制为只有一个 session ,您可以拥有多个角色用户。

并在 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
}

Note : The above code has been tested and working as expected in Grails version 2.4.4 and spring security spring-security-core:2.0.0 plugin

关于spring - 如何在并发 session 访问中使上一个 session 到期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43038645/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com