SameSite cookie in Java application

javax.servlet.http.cookie samesite
how to set samesite cookie attribute in java spring
how to set samesite cookie attribute in spring boot
java cookie samesite=none
how to set samesite cookie attribute in tomcat
how to set samesite cookie attribute in javascript
jsessionid samesite
java web xml samesite

Do you know any Java cookie implementation which allows to set a custom flag for cookie, like SameSite=strict? It seems that javax.servlet.http.Cookie has a strictly limited set of flags which can be added.

I am not a JEE expert, but I think that because that cookie property is a somewhat new invention, you cannot expect it to be present in Java EE 7 interfaces or implementations. The Cookie class is missing a setter for generic properties, as it seems. But instead of adding the cookie to your HttpServletResponse via


you can simply set the corresponding HTTP header field via

response.setHeader("Set-Cookie", "key=value; HttpOnly; SameSite=strict")

Update: Thanks to @mwyrzyk for pointing out that setHeader() overwrites all existing headers of the same name. So if you happen have other Set-Cookie headers in your response already, of course you would use addHeader() with the same parameters instead.

SameSite cookie in Java application, Bottomline is Servlet API has not implemented SameSite and so not in Java based frameworks or config file changes in application server� Cross-site requests nested within a page can fail after browser updates that change the default behavior of HTTP Cookies without the SameSite attribute.  The affected requests are sent to hostnames within separate registered domains, not just separate hostnames under the same domain.Full technical details of the SameSite attribute are available in the following RFC: https

If you don't wanna update all your code, you can also achieve same by one line config using Apache or Nginx configuration(or any other HTTP server/proxy that you are using)

1 Setting SameSite cookies using Apache configuration

You can add the following line to your Apache configuration

Header always edit Set-Cookie (.*) "$1; SameSite=Lax"

and this will update all your cookies with SameSite=Lax flag

See more here:

2 Setting SameSite cookies using Nginx configuration
location / {
    # your usual config ...
    # hack, set all cookies to secure, httponly and samesite (strict or lax)
    proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";

Same here, this also will update all your cookies with SameSite=Lax flag

See more here:

SameSite cookie SOLUTION for Java based deployments, Cookies. For Java users, we now recommend using `Cookie.builder` to create new cookies, for example: ```java. Cookie cookie = Cookie.builder("color", "blue"). Specific details on differences in SameSite cookie handling included in the.NET Framework 4.7.2 patch are described in this article. With the.NET Framework patch installed, the.NET Framework changes the defaults for the cookieSameSite configuration property for Session State and Forms Authentication to “Lax”.

As of today (24.01.20) servlet-api does not let to set sameSite attribute to the cookie. BTW there is an ongoing ticket (LINK) which will release a new (5.0 or 5.1 servlet-api).

Option 1: You are not in a hurry and can wait for servlet-api version, where Cookie class and SessionCookieConfig class have dedicated methods to set sameSite attribute.

Option 2: You are using an old version of servlet-api (e.g. 3.1), consequently old version of Tomcat (e.g. I am having current situation now). It means even when community releases servlet-api with sameSite support, you can not immediately update you version, because it can be too risky to update couple of major versions. In this case we have found a solution. There is a Cookie Processor ComponentLINK in Tomcat, which

The CookieProcessor element represents the component that parses received cookie headers into javax.servlet.http.Cookie objects accessible through HttpServletRequest.getCookies() and converts javax.servlet.http.Cookie objects added to the response through HttpServletResponse.addCookie() to the HTTP headers returned to the client.

The usage of this processor is quite straight forward. Inside of context.xml:

    <CookieProcessor sameSiteCookies="none"/>

In this case default implementation of processor is used (org.apache.tomcat.util.http.Rfc6265CookieProcessor), but you can specify any other within an CookieProcessor attribute className.

Add cookie SameSite attribute and use for session and flash � Issue , Do you know any Java cookie implementation which allows to set a custom flag for cookie, like SameSite=strict? It seems that javax.servlet.http.Cookie has a� Explicitly state cookie usage with the SameSite attribute #. The introduction of the SameSite attribute (defined in RFC6265bis ) allows you to declare if your cookie should be restricted to a first-party or same-site context. It's helpful to understand exactly what 'site' means here.

If you have existing code, no doubt you've used the java servlet Cookie object. We certainly have, so we wanted the least disruptive option. @kriegaex's answer is clean and concise, but is basically hard coding the cookie and doesn't reuse the cookie object. To expand on his answer, we wrote this function to handle the same site functionality, while at the same time, maintaining the existing Cookie object functionality. This answer is intended to be used in cases where you need to add multiple cookies on your response object, without making changes to existing cookies that may already be on the headers. The other option of course is to write a new cookie class and extend the functionality, but that requires even more changes to existing code than what we've come up with here.

Note that with this solution, only one line of existing code (per cookie) changes in order to add the same site functionality.

Sample usage:

// Existing code that doesn't change:   
Cookie cookie1=new Cookie("cookie1",Util.encodeURL(id));

Cookie cookie2=new Cookie("cookie2",Util.encodeURL(id));

// Old Code that is replaced by new code
// httpResponse.addCookie(cookie1);
// httpResponse.addCookie(cookie2);

// New Code - see static helper class below
HttpService.addCookie(httpResponse, cookie1, "none");
HttpService.addCookie(httpResponse, cookie2, "Strict");

Example response headers when using cURL:

< HTTP/1.1 200 OK
< Connection: keep-alive
< X-Powered-By: Undertow/1
< Set-Cookie: cookie1=f871c026e8eb418c9c612f0c7fe05b08; path=/; SameSite=none; secure
< Set-Cookie: cookie2=51b405b9487f4487b50c80b32eabcc24; path=/; SameSite=Strict; secure
< Server: WildFly/9
< Transfer-Encoding: chunked
< Content-Type: image/png
< Date: Tue, 10 Mar 2020 01:55:37 GMT

And finally, the static helper class:

public class HttpService {
    private static final FastDateFormat expiresDateFormat= FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss zzz", TimeZone.getTimeZone("GMT"));

    public static void addCookie(HttpServletResponse response, Cookie cookie, String sameSite) {

        StringBuilder c = new StringBuilder(64+cookie.getValue().length());


        append2cookie(c,"domain",   cookie.getDomain());
        append2cookie(c,"path",     cookie.getPath());
        append2cookie(c,"SameSite", sameSite);

        if (cookie.getSecure()) {
            c.append("; secure");
        if (cookie.isHttpOnly()) {
            c.append("; HttpOnly");
        if (cookie.getMaxAge()>=0) {
            append2cookie(c,"Expires", getExpires(cookie.getMaxAge()));

        response.addHeader("Set-Cookie", c.toString());

    private static String getExpires(int maxAge) {
        if (maxAge<0) {
            return "";
        Calendar expireDate = Calendar.getInstance();
        expireDate.setTime(new Date());

        return expiresDateFormat.format(expireDate);

    private static void append2cookie(StringBuilder cookie, String key, String value) {
        if (key==null || 
                value==null || 
                || value.trim().equals("")) {

        cookie.append("; ");

Setting the SameSite Attribute on the JSESSIONID cookie for Java , the `SameSite` cookie attribute for your application-defined cookies, The Servlet specification does not offer any API to set the SameSite� Session state cookie with SameSite=None. The session cookie is emitted during the Session_Start event handling logic. Hence, we can modify this logic to incorporate additional code to decorate the session cookie as needed. Here is how the Session_Start code would look like:

I found that our cookies which were being created on a successful return were not changed by "Header edit" or "Header always edit". Apparently apache has two buckets of cookies - see this

What did work for me was

Header onsuccess edit Set-Cookie (.*) "$1; SameSite=Lax"

SameSite cookie in Java application-漫漫字节|漫漫编程, Add the "SameSite" attribute to the cookie. This limits the scope of the cookie such that it will only be attached to same site requests if "Strict" or cross-site requests� If the "None" value is specified for the SameSite attribute on a site, then a Secure attribute also needs to be specified, which causes the cookie data to use the more secure HTTPS protocol

Setting the SameSite attribute on cookies with Open Liberty, What are third-party cookies? What are cross-site request? When you visit a website, a browser cookie is generated and saved inside a folder in� After receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header. An expiration date or duration can be specified, after which the cookie is no longer sent.

ResponseCookie.ResponseCookieBuilder (Spring Framework 5.2.8 , Do you know any Java cookie implementation which allows to set a custom flag for cookie, like SameSite=strict? It seems that javax.servlet.http.

Chrome's Changes Could Break Your App: Prepare for SameSite ,

  • On the server side or on the client site, e.g. when testing with Selenium?
  • from server side
  • Are you aware of the fact that all you need to do is set an HTTP header? I am struggling to understand what you mean by "cookie implementation". Can you elaborate, please? You could edit your question and describe your current toolchain (e.g. JEE, Spring, application server or container and what else might be interesting). As it is, the question is too unspecific.
  • Maybe you misunderstand how StackOverflow works, even though with a reputation of 1.6k you should know better: It is your job to provide sample code, then people who feel inclined to answer can help you fix or improve it. Please learn how to ask a question on SO and provide a minimal, complete, and verifiable example. Thank you.
  • There are many solutions, based on Filters and HTTPHandlers, in…
  • Why the downvote? According to StackOverflow regulations, downvotes are reserved for sloppy answers of very low quality showing a significant lack of research effort or knowledge. At time of writing this, I was so far the only person talking to the OP and searching for a workaround, because what he wants is currently impossible. I even explained why it does not work the way he wishes. Even if you do not like my suggestion, you should not downvote it. Instead, you could provide a better solution.
  • Keep in mind that using setHeader() method will remove all previous headers with the same name so I had to do something like this
  • Thanks but this doesn't work if you have a path e.g. path / SameSite=None; results in "An invalid path ... was specified for this cookie".