Spring 4 Session Cookie change field

436 views Asked by At

I'm using Spring 4 and I create a Session using request.getSession()

I've observed that a SESSION cookie is created. The Response header contains as follows:

Set-Cookie: SESSION=ZTgwZWMxMDItOTA1MC00ZTZjLWIxMmUtZmM3NmQxNzJmNDBm; Path=/myApp/; Secure; HttpOnly

In the Cookie created, I need SameSite=Lax. Currently, there is no value of SameSite.

So in my code, I did the following attempting to overwrite the SESSION cookie.

// request is of type HttpServletRequest
// response is of type HttpServletResponse
HttpSession session = request.getSession(); 
String base64value = Base64.getEncoder().encodeToString(session.getId().getBytes());
response.setHeader("Set-Cookie","SESSION=" + base64value + ";path=/myApp/ ;HttpOnly ;Secure;SameSite=lax");

But now 2 SESSION cookies are created, and can be seen in response headers:

Set-Cookie: SESSION=ZTgwZWMxMDItOTA1MC00ZTZjLWIxMmUtZmM3NmQxNzJmNDBm;path=/myApp/ ;HttpOnly ;Secure;SameSite=lax
Set-Cookie: SESSION=ZTgwZWMxMDItOTA1MC00ZTZjLWIxMmUtZmM3NmQxNzJmNDBm; Path=/myApp/; Secure; HttpOnly

How can I have just 1 SESSION cookie with SameSite=Lax with Spring 4?

1

There are 1 answers

0
rowan_m On

You are manually sending the Set-Cookie header which is duplicating the header set by Spring's session management.

If Spring 4 allows setting the SameSite attribute for the session cookie (unfortunately, I can't find the docs for this so can't be sure) then I would expect it to be in your web.xml:

<session-config>
    <cookie-config>
        <http-only>true</http-only>
        <secure>true</secure>
        <!-- Maybe there's a SameSite option? -->
    </cookie-config>
</session-config>