首页 > 解决方案 > Spring Boot 2 Set-Cookie 响应标头丢失

问题描述

请原谅缺乏结构/礼仪,这是我的第一篇文章。

我有一个使用 Spring Boot (v2.1.6) 的 Java 应用程序,该应用程序具有基于注释的 spring-boot-starter-security 配置,并且无法理解如何添加以下响应标头:

 "Set-Cookie: SameSite=strict"

解决警告:

A cookie associated with a cross-site resource at "myApiUrl" was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

下面列出了我的 HttpSecurity 的完整配置,我尝试使用 StaticHeadersWriter 在配置的最后部分添加标头,如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception { 
    http
    .csrf().disable()
    .cors()
    .and()
        .exceptionHandling()
        .authenticationEntryPoint(entryPoint) //request is generally sent to entry point when unauthorized
    .and()
    .authorizeRequests()
        .antMatchers("/loggedIn").permitAll()
        .antMatchers("/createUser").permitAll()
        .antMatchers("/deleteUser").hasRole("ADMIN")
        .antMatchers("/fullDB").hasRole("ADMIN")
        .antMatchers("/logs").hasRole("ADMIN")
        .antMatchers("/**").authenticated()
    .and()
    .formLogin()
        .successHandler(new AuthenticationSuccessHandler())
        .failureHandler(new SimpleUrlAuthenticationFailureHandler())
    .and()
    .logout()
        .deleteCookies(cookieName)
        .invalidateHttpSession(true)
        .logoutUrl("/logout")
        .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)))
    .and()
        .headers()
        .addHeaderWriter(new StaticHeadersWriter("Set-Cookie", "SameSite=strict"))
        .addHeaderWriter(new StaticHeadersWriter("A-cookie","B=val"))
        .addHeaderWriter(new StaticHeadersWriter("SetCookie","SameSitestrict"));
}

使用以下配置,除了 Set-Cookie 标头之外,我能够收到每个标头的有效响应,该标头似乎已被删除,可以在下面的链接中看到。

响应图像

我尝试解决此问题的其他尝试包括在提供的 successHandler() 中将重定向添加到自定义 url 端点,然后它将返回一个 ResponseEntity 我可以在其中提供下面的代码,但是这些尝试也不会具有“设置-Cookie”响应标头包括在内。

   HttpHeaders httpHeaders = new HttpHeaders();
   httpHeaders.add(HttpHeaders.SET_COOKIE, "SomeName=someId");
   return new ResponseEntity(httpHeaders, HttpStatus.OK);

 or

   response.addCookie(new Cookie("SomeName", "someId"));
   return ResponseEntity.ok().build();

任何有关如何在 Spring Boot API 调用的响应中提供“Set-Cookie”标头以解决此 chrome 警告的建议将不胜感激!

标签: javaspringspring-bootspring-security

解决方案


推荐阅读