Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SameSite cookie in 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.

like image 959
Michal_Szulc Avatar asked Mar 10 '17 11:03

Michal_Szulc


People also ask

What is the use of SameSite cookie?

Overview. SameSite prevents the browser from sending this cookie along with cross-site requests. The main goal is to mitigate the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks.

How do I set SameSite cookies?

To prepare, Android allows native apps to set cookies directly through the CookieManager API. You must declare first party cookies as SameSite=Lax or SameSite=Strict , as appropriate. You must declare third party cookies as SameSite=None; Secure .

Where do I put SameSite attributes?

You can add SameSite cookie attributes in the set-cookie HTTP response header to restricts browser behavior. It may prevent the browser from sending the cookie's key=value pair based on the type of interaction that triggered the HTTP request.


1 Answers

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.

like image 92
kriegaex Avatar answered Sep 21 '22 07:09

kriegaex