我做了以下事情:
- 登录到我的 spring 应用程序(例如,作为用户“admin”)
- 停止tomcat
- 现在我看到 session 被序列化到 sessions.ser 文件中
- 我重启tomcat
- session.ser 文件消失了(我猜它在服务器启动期间被反序列化了?)
- 现在我发送一个要求登录用户的请求(如上所示 在第 1 步中,即我在之前已经登录的浏览器中按 F5,所以我猜请求会发送 jSessionId 等)
- 在调试的时候可以观察到spring是如何成功加载SecurityContext的
HttpSessionSecurityContextRepository.readSecurityContextFromSession
使用存储的 Session-Information(它是一个 UsernamePasswordAuthenticationToken,包含一个包含 Principal 等的 Authentication 对象。因此似乎可以获取自定义 User 对象)
- Spring 接受请求,即不需要重新登录并发送适当的响应
但是,当尝试通过 SessionRegistry
列出登录用户时
for (Object principal : sessionRegistry.getAllPrincipals()) {
MyCustomUser myCustomUser = (MyCustomUser) principal;
ClientQueryDetails client = clientQuery.getDetails(myCustomUser
.getClientId()).get();
List<SessionInformation> sessions = sessionRegistry.getAllSessions(
principal, false);
for (SessionInformation sessionInformation : sessions) {
result.add(new SessionInfo(client.getName(), myCustomUser
.getUsername(), sessionInformation.getSessionId(),
sessionInformation.getLastRequest()));
}
}
正如我通常所做的那样可视化当前 Activity 的用户/ session ,它是空的。
为什么Spring此时不把那些Principals添加到SessionRegistry中呢? 我可以/应该以某种方式手动完成吗?
我读过 https://github.com/spring-projects/spring-security/issues/2062听起来这样做不是个好主意。
似乎也相关Getting logged in users with sessionRegistry not work when manually authenticate
总结一下我的问题:
- 为什么 spring 不将序列化的 session 信息重新添加到
SessionRegistry
中? - 查询
SessionRegistry
以向用户(即登录用户)显示所有 Activity session 的正确方法是否正确? 编辑 是的,这绝对是 SessionRegisty 的目的:https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#list-authenticated-principals 我应该手动将
Principal
添加到 SessionRegistry 吗? 编辑 https://github.com/spring-projects/spring-security/issues/2062提供了将 session 手动读取到 SessionRegistry 的不同方法,但这样做似乎有一些注意事项。sessions.ser 中的 Session 在哪里以及如何被反序列化为 spring 在哪里获取它?或者换句话说, session 信息如何从 sessions.ser 文件获取到 spring 的
SecurityContext
中?特别是它是如何从tomcat“交接”给spring的?
最佳答案
对于在 SessionRegistry 中看不到 session 但具有有效 session (即登录用户)的问题,我的解决方案是简单地在服务器重启时删除 SESSIONS.ser 文件。
因此,所有用户都必须重新登录,并相应地填充 SessionRegistry。由于我没有让 session 保持 Activity 的迫切需要,这对我来说是一个很好的解决方案。
关于java - 如何获取序列化的tomcat HttpSession以重新填充spring SessionRegistry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432271/