Java 使用 Spring Security 检索会话 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3542026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieving Session ID with Spring Security
提问by abyx
For logging purposes, I'd like to create a logger that automatically adds the current session's ID to logged lines.
For logged in users this isn't a problem:
出于记录目的,我想创建一个记录器,它会自动将当前会话的 ID 添加到记录的行中。
对于登录用户,这不是问题:
((WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails())
.getSessionId()
The problem is, before the user has logged in getAuthentication()
returns null
. Is there another way for getting the session ID without having a reference to the current response or anything of that sort?
问题是,在用户登录之前getAuthentication()
返回null
。是否有另一种方法可以在不引用当前响应或任何类似内容的情况下获取会话 ID?
采纳答案by axtavt
You may use
您可以使用
RequestContextHolder.currentRequestAttributes().getSessionId();
This relies on Spring's RequestContextHolder
, so it should be used with Spring MVC's DispatcherServlet
or you should have a RequestContextListener
declared. Also session will be created if not exists.
这依赖于 Spring 的RequestContextHolder
,所以它应该与 Spring MVC 一起使用,DispatcherServlet
或者你应该有一个RequestContextListener
声明。如果不存在,也会创建会话。