Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 442
Nikolas Soares Avatar asked Oct 15 '19 01:10

Nikolas Soares


People also ask

How do I set cookies to the same site?

Android System WebView To prepare, Android allows native apps to set cookies directly through the CookieManager API. You must declare first party cookies as SameSite=Lax or SameSite=Strict , as appropriate. You must declare third party cookies as SameSite=None; Secure .

Is same site supported cookie flag?

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers. The SameSite attribute of the Set-Cookie HTTP response header allows you to declare if your cookie should be restricted to a first-party or same-site context.

How do you set a SameSite flag?

Enable the new SameSite behavior If you are running Chrome 91 or newer, you can skip to step 3.) Go to chrome://flags and enable (or set to "Default") both #same-site-by-default-cookies and #cookies-without-same-site-must-be-secure. Restart Chrome for the changes to take effect, if you made any changes.


1 Answers

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");
  }
}
like image 84
Mohsin Mansoor Avatar answered Jan 08 '23 12:01

Mohsin Mansoor