使用Spring Security检索会话ID [英] Retrieving Session ID with Spring Security
问题描述
出于记录目的,我想创建一个记录器,自动将当前会话的ID添加到记录的行。
对于登录用户,这不是问题:
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:
((WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails())
.getSessionId()
问题是,在用户登录之前 getAuthentication()
返回空
。是否有另一种方法来获取会话ID而没有引用当前响应或任何类型的东西?
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?
谢谢!
推荐答案
你可以使用
RequestContextHolder.currentRequestAttributes().getSessionId();
这依赖于Spring的 RequestContextHolder
,所以它应该与Spring MVC的 DispatcherServlet
一起使用,或者你应该声明一个 RequestContextListener
。如果不存在,也会创建会话。
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 Security检索会话ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!