I tried to find out how to use SameSite cookie with Spring Boot (Spring Web MVC + Tomcat).
See the MDN documentation.
Tomcat serializes the javax.servlet.http.Cookie to a string in order to write the cookie to the HTTP response.
Serialization is done through the ʻorg.apache.tomcat.util.http.CookieProcessor interface. ʻOrg.apache.tomcat.util.http.Rfc6265CookieProcessor is provided as an implementation class, but you can add the SameSite attribute using the setSameSiteCookies method of this Rfc6265CookieProcessor class.
The Rfc6265CookieProcessor set to add the SameSite attribute must be set in ʻorg.apache.catalina.Context`, but for the time being, if it can be used in Spring Boot, that's fine, so we will skip the customization method with Tomcat alone.
In Spring Boot, you can customize Tomcat's Context by providing a component that implements the ʻorg.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer` interface.
You can add the SameSite attribute to a cookie with the following implementation class.
package com.example;
import org.apache.catalina.Context;
import org.apache.tomcat.util.http.Rfc6265CookieProcessor;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.stereotype.Component;
@Component
public class SameSiteCookieTomcatContextCustomizer implements TomcatContextCustomizer {
@Override
public void customize(final Context context) {
final Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor();
cookieProcessor.setSameSiteCookies("Lax");
context.setCookieProcessor(cookieProcessor);
}
}
--Complete code example https://github.com/backpaper0/spring-boot-sandbox/tree/master/samesite-cookie-demo
As @tokuhirom told me, [When using Spring Session, SameSite attribute is added by default](https://github.com/spring-projects/spring-session/blob/2.2.0.RELEASE/spring -session-core / src / main / java / org / springframework / session / web / http / DefaultCookieSerializer.java # L88) It seems.
I found that there are two ways to use SameSite cookie in Spring Boot (Spring Web MVC + Tomcat).
--Prepare a component that implements TomcatContextCustomizer and set the customized Rfc6265CookieProcessor in Context.
--Use Spring Session
Recommended Posts