开发者

Retrieving Session ID with Spring Security

开发者 https://www.devze.com 2023-01-12 09:34 出处:网络
For logging purposes, I\'d like to create a logger that automaticall开发者_如何学JAVAy adds the current session\'s ID to logged lines.

For logging purposes, I'd like to create a logger that automaticall开发者_如何学JAVAy adds the current session's ID to logged lines.

For logged in users this isn't a problem:

((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?


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.


More easiest way is:

@GetMapping(path = "/foo")  
public void foo(HttpSession session) {  
    String sessionId = session.getId();  
}


If you visit this topic to find solution in WebSockets, maybe the following can be useful for you;

@MessageMapping("/message")
public void message(@Header("simpSessionId") String sessionId) {
    // ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号