【问题标题】:spring security - sessionId is null in authenticationspring security - sessionId 在身份验证中为空
【发布时间】:2026-01-31 02:15:02
【问题描述】:

我有以下功能

@Override
public void onAuthenticationSuccess(HttpServletRequest request
        , HttpServletResponse response, Authentication authentication)
           throws IOException, ServletException {

      String sessionId = ((WebAuthenticationDetails) authentication
            .getDetails()).getSessionId();

}

我正在尝试使用以下代码对服务器进行身份验证:

 HttpClient client = new HttpClient();
 CommonsClientHttpRequestFactory commons 
         = new CommonsClientHttpRequestFactory(client);

 RestTemplate template = new RestTemplate(commons);
 MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>()
 map.add("j_username", "11");
 map.add("j_password", "22");           
 Object result2 = template.postForObject(
        "http://localhost:8080/APP/j_spring_security_check", map,Object.class);

问题是,凭据是合法的,我确实输入了 onSuccess,但每次我使用上面的代码时 sessionId 都是空的。

当我通过表单进行身份验证时,它会创建一个会话 ID。 当我设置

 <security:http create-session="always" />

它确实有效。但我相信这每次都会打开一个会话,并且可能真的效率低下。

知道为什么会话 id 在 java 发布请求中为空,而表单却不是吗?以及如何解决?

谢谢!

【问题讨论】:

    标签: java spring rest authentication spring-security


    【解决方案1】:

    如果没有看到应用程序的其余部分和 Spring Security 配置,很难说。您可以使用 &lt;debug&gt; 元素轻松启用 Spring Security 调试,该元素将提供在登录表单案例中创建会话的位置的堆栈跟踪。我猜这可能是因为您的应用程序正在使用 JSP,并且当您查看登录表单时 JSP 正在创建会话。在使用 RestTemplate 发布的情况下,它在您提交用户名和密码之前不会创建会话(onSuccess 的会话是您提交凭据之前的会话)。

    【讨论】:

    • 显然过滤器链不可见,并且当我不使用'create-session="always"'时没有创建会话