Spring: Unable to set SameSite cookie to None

Ahmad.Masood picture Ahmad.Masood · Aug 10, 2019 · Viewed 15.5k times · Source

I'm unable to set SameSite cookie value to None.

Following is how i'm generating ResponseCookie object.

ResponseCookie cookie = ResponseCookie.from("Hb", cookieUserId)
            .maxAge(!isEmpty(cookieUserId) ? MAX_COOKIE_DURATION : 0)
            .domain("test.com")
            .sameSite("None")
            .secure(true)
            .path("/")
            .build();
 response.addCookie(cookie)

Curl request to endpoint

curl -X POST "localhost:8080/v1/user/v" --data "{}" -v -H 'Content-Type: application/json'

Response:

< set-cookie: Hb=00b7be31-fc6d-4891-a07c-46b5ef2b423c; Max-Age=7776000; Expires=Fri, 8 Nov 2019 17:23:52 GMT; Path=/; Domain=test.com; Secure

As you can see SameSite attribute is missing from the cookie.

Spring Boot (version: 2.1.3.RELEASE) dependency

        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

Answer

rowan_m picture rowan_m · Aug 14, 2019

I think the issue is that the underlying javax.servlet.http.Cookie does not support the SameSite attribute, let alone the new None value.

Instead you can set this directly as a header, assuming your response is an instance of javax.servlet.http.HttpServletResponse:

ResponseCookie cookie = ResponseCookie.from("Hb", cookieUserId)
            .maxAge(!isEmpty(cookieUserId) ? MAX_COOKIE_DURATION : 0)
            .domain("test.com")
            .sameSite("None")
            .secure(true)
            .path("/")
            .build();
 response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());