This article will provide a walk through the configuration of the SameSite attribute for Cookies in Spring Boot application. Please note that this tutorial applies to Spring Boot 2.6 and newer applications.
SameSite overview
SameSite is a particular cookie that you can use for security purposes. It prevents the browser from sending the cookie from domains other than the original one, avoiding cross-site request forgery (CSRF) attacks. The flag can typically have a lax or strict value.
- The strict value indicates a restrictive policy. So, if I link to an external site I won’t take the cookie of that site: so a big difference from the classic behavior of the web in the past. For an online banking site, at least on paper, this behavior is ideal.
- The lax value is slightly more usable and permissive. It allows you to set cookies from external websites that we link to on our page. At the same time you can prevent CSRF attacks via HTTP POST.
Configuring the Same Site attribute
If you want to change the SameSite attribute in a Spring Boot application, you can use the server.servlet.session.cookie.same-site property. You can configure this property in any of the embedded Web servers (Tomcat, Jetty and Undertow).
For example, if you want your session cookie to have a SameSite attribute of lax, configure application.properties as follows:
# SameSite Cookie Attribute server.servlet.session.cookie.same-site=lax
On the other hand, to enable cookies for cross-site access, use the “none” policy
server.servlet.session.cookie.same-site=none
Finally, to set the “none” policy using the application.yaml file, configure it as follows:
server: servlet: session: cookie: same-site: "none"
Programmatic configuration
Besides the declarative approach, you can also use a @Configuration Bean to apply a SameSite policy for all cookies with a name that matches the regular expression.
For example, the following Bean applies a SameSite of Lax for all cookies with a name that matches the regular expression myapp.*.
import org.springframework.boot.web.servlet.server.CookieSameSiteSupplier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class MySameSiteConfiguration { @Bean public CookieSameSiteSupplier applicationCookieSameSiteSupplier() { return CookieSameSiteSupplier.ofLax().whenHasNameMatching("myapp.*"); } }
Conclusion
This tutorial covered how to configure the SameSite Cookie attribute in Spring Boot 2.6 applications. If you want to learn how to apply the same policy in WildFly / JBoss application server check this article: Configuring the Same Site attribute in WildFly