有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尽管有无状态会话管理,JavaSpring还是添加了JSESSIONID

我正在使用我的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();
}

SessionCreationPolicy.STATELESS开始,我希望Spring不会自己创建会话。但是,如果我访问/login以外的任何其他资源,我仍然会在响应头中看到以下条目:

set-cookie: JSESSIONID=...; Path=/; HttpOnly

有人能解释一下这是从哪里来的(可能不是从Spring来的),如果它仍然是从Spring来的,还有什么需要改变的吗

编辑:

在我的控制器中测试时,会话仍然被注入,正如上面的令牌所示。我仍然不知道这是从哪里来的

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

共 (3) 个答案

  1. # 2 楼答案

    您当前的配置(sessionCreationPolicy(SessionCreationPolicy.STATELESS))确保了Spring安全性(且仅限于Spring安全性

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

    应用程序的任何其他组件(例如,如果使用Spring会话)仍然可以自由创建会话

  2. # 3 楼答案

    即使使用SessionCreationPolicy。无状态,仍然可以在spring安全性范围之外创建会话。例如,当您调用请求时。getSession()或请求。getSession(true),或者如果访问会话范围的bean(spring将在内部调用request.getSession(true))

    如果您在应用程序中添加以下内容。属性,每次创建会话时都会输出stacktrace,这可能有助于您了解发生了什么

    logging.level.org.springframework.session.web.http.SessionRepositoryFilter.SESSION_LOGGER=DEBUG