在我的应用程序中,我有一个管理员可以删除用户。所以当我从管理员会话中删除用户时,我希望被删除的用户应该自动注销。 我知道我要删除的用户的会话ID,但我不知道如何使用会话ID使会话失效。
我想要类似这样的东西:invalidate(SessionId);
有没有任何可能性?我认为可以使用过滤器并在每个请求上检查数据库,但是否有另一种方式,我不需要在每个HTTP请求上检查数据库呢?
谢谢:D
在我的应用程序中,我有一个管理员可以删除用户。所以当我从管理员会话中删除用户时,我希望被删除的用户应该自动注销。 我知道我要删除的用户的会话ID,但我不知道如何使用会话ID使会话失效。
我想要类似这样的东西:invalidate(SessionId);
有没有任何可能性?我认为可以使用过滤器并在每个请求上检查数据库,但是否有另一种方式,我不需要在每个HTTP请求上检查数据库呢?
谢谢:D
我认为可以使用Spring Security基础设施来解决问题,使用SessionRegistry类。
您需要在web.xml
中注册HttpSessionEventPublisher
:
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
SessionRegistry
来检索用户的SessionInformation
并调用expireNow
。在用户的下一个请求中,servlet过滤器应使HttpSession过期。有关其工作原理的一些说明,请参阅SessionInformation的javadoc。// to end a session of a user:
List<SessionInformation> sessions = sessionRegistryImpl.getAllSessions(user, false);
sessionRegistryImpl.getSessionInformation(sessions.get(0).getSessionId()).expireNow();
// note: you can get all users and their corresponding session Ids:
List<Object> users = sessionRegistryImpl.getAllPrincipals();
List<String> sessionIds = new ArrayList<>(users.size());
for (Object user: users) {
List<SessionInformation> sessions = sessionRegistryImpl.getAllSessions(user, false);
sessionIds.add(sessions.get(0).getSessionId());
}
expireNow
方法。 - zygimantusweb.xml
中注册HttpSessionEventPublisher
并声明SessionRegistry
吗? - Alex78191// expire and remove the user's sessions from Spring session registry
List<Object> principals = sessionRegistry.getAllPrincipals();
for (Object principal : principals) {
List<SessionInformation> sessions = sessionRegistry.getAllSessions(principal, true);
for (SessionInformation sessionInfo : sessions) {
if (authentication.getPrincipal().equals(sessionInfo.getPrincipal())) {
if (!sessionInfo.isExpired()) sessionInfo.expireNow();
sessionRegistry.removeSessionInformation(sessionInfo.getSessionId());
}
}
}
如果使用XML配置来连接您的Spring Session Registry,它可能看起来像这样:
<beans:bean id="sessionRegistry"
class="org.springframework.security.core.session.SessionRegistryImpl" />
除了@LaurentG所建议的内容外,您的Spring配置文件还需要添加以下内容:
<session-management>
<concurrency-control session-registry-alias="sessionRegistry" />
</session-management>
为了使其工作。此外,@zygimantus的答案可用于访问会话数据。
<concurrency-control session-registry-alias="sessionRegistry" />
is the same as <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
- Alex78191