【问题标题】:Retrieving Session ID with Spring Security使用 Spring Security 检索会话 ID
【发布时间】:2011-04-02 07:19:00
【问题描述】:

出于记录目的,我想创建一个记录器,自动将当前会话的 ID 添加到记录的行中。
对于已登录的用户,这不是问题:

((WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails())
    .getSessionId()

问题是,在用户登录之前getAuthentication() 返回null。是否有另一种方法可以在不引用当前响应或任何类似内容的情况下获取会话 ID?

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    你可以使用

    RequestContextHolder.currentRequestAttributes().getSessionId();
    

    这依赖于 Spring 的 RequestContextHolder,因此它应该与 Spring MVC 的 DispatcherServlet 一起使用,或者你应该声明一个 RequestContextListener。如果不存在,也会创建会话。

    【讨论】:

    • @axtavt 我有 angular appli 在 diffrnt 端口中运行,服务器代码在 diffrnt 端口中运行。在我的服务器代码中实现了 Spring Security,如果成功,它会重定向到另一个 Java 控制器,因为我包装了所有用户角色和其他信息。但我只得到一个anonymusUser,因为我的重定向网址中没有cookie。是不是克服了你的解决方案..
    【解决方案2】:

    更简单的方法是:

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

    【讨论】:

      猜你喜欢
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 2015-12-06
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多