How to set same-site cookie flag in Spring Boot?

Nikolas Soares picture Nikolas Soares · Oct 15, 2019 · Viewed 32.2k times · Source

Is it possible to set Same-Site Cookie flag in Spring Boot?

My problem in Chrome:

A cookie associated with a cross-site resource at http://google.com/ 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.


How to solve this problem?

Answer

Mohsin Mansoor picture Mohsin Mansoor · Oct 21, 2019

This is an open issue with Spring Security (https://github.com/spring-projects/spring-security/issues/7537)

As I inspected in Spring-Boot (2.1.7.RELEASE), By Default it uses DefaultCookieSerializer which carry a property sameSite defaulting to Lax.

You can modify this upon application boot, through the following code.

Note: This is a hack until a real fix (configuration) is exposed upon next spring release.

@Component
@AllArgsConstructor
public class SameSiteInjector {

  private final ApplicationContext applicationContext;

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
    DefaultCookieSerializer cookieSerializer = applicationContext.getBean(DefaultCookieSerializer.class);
    log.info("Received DefaultCookieSerializer, Overriding SameSite Strict");
    cookieSerializer.setSameSite("strict");
  }
}