How to set SameSite attribute?

2020-04-11 10:41发布

问题:

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.

回答1:

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"));
    }


回答2:

In etc/apache2/httpd.conf

Header edit Set-Cookie ^(.*)$ $1;SameSite=Strict


works for me.....



回答3:

New Tomcat supports SameSite cookies via TomcatContextCustomizer.

  • for Spring Boot in could be done in @Configuration, see https://stackoverflow.com/a/60860531/548473
  • for Tomcat application - in context.xml, see https://stackoverflow.com/a/57622508/548473