Search code examples
javacookiescsrfflags

How to set 'SameSite' on a cookie from within a Java application?


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.


Solution

  • 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

    response.addCookie(myCookie)
    

    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.


    Update: Starting with Jakarta Servlet API, generic getAttribute() and setAttribute() methods have been added to the Cookie class.