Search code examples
springspring-mvchttpcookie

Why the cookie details returned by @CookieValue is null?


I have a controller in which I am trying to get the values of cookie by using the

@PostMapping(SIGNOUT)
    @ResponseStatus(value=HttpStatus.OK)
    public void signoutUser(@CookieValue(name="acctk") Cookie cookie ,final HttpServletRequest request, final HttpServletResponse response) {
        System.out.println("value: " + cookie.getValue());
        System.out.println("path: " + cookie.getPath());
        System.out.println("domain: " + cookie.getDomain());
        System.out.println("max-age: " + cookie.getMaxAge());
        System.out.println("is secure: " + cookie.getSecure());
}

The controller is returning:

value: 3C6E523D68F35294D3D6AC099CDA60EB
path: null
domain: null
max-age: -1
is secure: false

The cookie sent with request:

acctk=3C6E523D68F35294D3D6AC099CDA60EB; Max-Age=2592000; Expires=Tue, 16-Apr-2019 13:52:12 GMT; Path=/api/v1; HttpOnly

So, by the result, only the cookie value(and secure) is correct and other details are not. Why such behavior?


Solution

  • Because the browser receives all this information from the cookie set in the response using the Set-Cookie header, but it only sends the cookie value to the server in the Cookie header.

    See https://en.wikipedia.org/wiki/HTTP_cookie, and https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie.

    Note, BTW, that the annotation is named CookieValue. There's a reason for that name.