尽管无状态会话管理,Spring添加了一个JSESSIONID

Gla*_*ins 9 java spring spring-security

我使用以下配置对我的Web应用程序进行了有效的JWT身份验证:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
      .csrf().disable()
      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
      .exceptionHandling()
      .authenticationEntryPoint(
          (req, rsp, e) -> p.sendError(HttpServletResponse.SC_UNAUTHORIZED))
      .and()
      .addFilter(new UsernamePasswordAuthenticationFilter(authenticationManager(),
          jwtConfig))
      .addFilterAfter(new JwtTokenAuthenticationFilter(jwtConfig),
          UsernamePasswordAuthenticationFilter.class)
      .authorizeRequests()
      .antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
      .anyRequest().authenticated();
}
Run Code Online (Sandbox Code Playgroud)

因为SessionCreationPolicy.STATELESS我期待Spring不会创建会话本身.但是,如果我访问任何其他资源/login,我仍然会在响应标头中看到以下条目:

set-cookie: JSESSIONID=...; Path=/; HttpOnly
Run Code Online (Sandbox Code Playgroud)

有人可以解释它来自哪里(也许不是来自Spring),如果它仍然来自Spring,那么需要改变什么?

编辑:

在我的控制器中进行测试,会话仍按照上述令牌所示进行注入.我仍然不知道这是从哪里来的.

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(HttpSession session) {
    if (session != null) {
        System.out.println("Session is existing"); // executes
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

您当前的配置 ( sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 确保 Spring-Security (且仅 Spring-Security

  • 不会创建会话
  • 不会依赖会话来提供身份验证详细信息(例如,提供Principal)。

应用程序的任何其他组件(例如,如果您要使用 Spring-Session)仍然可以自由创建 session

  • 然后我仍然不知道会话来自哪里。我已进行编辑以确认会话已注入。除了安全配置和 JWT 身份验证之外,这只是一个简单的请求。还有其他想法吗? (2认同)