I have a problem with setting SameSite attribute in Cookie. I wanted to set this attribute, but neither javax.servlet.http.Cookie
nor java.net.HttpCookie
provide method to deal with it. Therefore, I have an idea to create a response javax.servlet.Filter
that catch "Set-Cookie" header and add "SameSite=Strict" attribute.
response.setHeader("Set-Cookie", response.getHeader("Set-Cookie") + "; SameSite=strict");
It works ok but problem appeares when I have more than one "Set-Cookie" header in one response. javax.servlet.http.HttpServletResponse
does not provide method to remove or overwrite more than one heder with the same name (iterating over them and using setHeader()
doesn't work because it always sets the last one). Do you have any idea how to set SameSite attribute to cookie or how to overwrite headers in response filter?
Thanks in advance.
Filter that catch "Set-Cookie" header and add "SameSite=Strict" attribute. response. setHeader("Set-Cookie", response. getHeader("Set-Cookie") + "; SameSite=strict");
SameSite cookie attribute is used by browsers to identify how first- and Third-Party Cookies should be handled. Browsers can either allow or block such cookies depending on attribute and scenario.
If you wanna add the SameSite option to the cookies in your application, you can configure the Tomcat Cookie Processor (the CookieProcessor ) in the META-INF/context. xml . NOTE: This configuration may fail in older versions of Tomcat. Apparently, these options work well if you use, at least, Tomcat 8.5.
A New Model for Cookie Security and Transparency Developers must use a new cookie setting, SameSite=None , to designate cookies for cross-site access. When the SameSite=None attribute is present, an additional Secure attribute must be used so cross-site cookies can only be accessed over HTTPS connections.
It turns out that using setHeader()
method remove all previous headers with the same name so I just create simple for loop in doFilter()
method. It adds SameSite=Strict
attribute to every cookie that is set.
boolean firstHeader = true;
for (String header : cookiesHeaders) {
if (firstHeader) {
httpResponse.setHeader("Set-Cookie",
String.format("%s; %s", header, "SameSite=Strict"));
firstHeader = false;
continue;
}
httpResponse.addHeader("Set-Cookie",
String.format("%s; %s", header, "SameSite=Strict"));
}
In etc/apache2/httpd.conf
Header edit Set-Cookie ^(.*)$ $1;SameSite=Strict
works for me.....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With