I just tried setting (actually, deleting - via max age set to 0) a session cookie, when I detect a specific client error. The HTTP response I am using is from the 4xx category (e.g. 401, 406, etc).
The cookie deletion works fine with this kind of response generated on the server side:
Response resp = Response.status(Response.Status.OK).header(
"Set-Cookie",
cookieName+"="+sessionId+"; "+
"Version=1; Max-Age=0; Path=" + cookiePath + "; " +
"Expires=Thu, 01 Jan 1970 00:00:00 GMT").entity("").build();
...but fails with this:
Response resp = Response.status(Response.Status.UNAUTHORIZED).header(
"Set-Cookie",
cookieName+"="+sessionId+"; "+
"Version=1; Max-Age=0; Path=" + cookiePath + "; " +
"Expires=Thu, 01 Jan 1970 00:00:00 GMT").entity("").build();
(Only difference: 200 => 406).
Is it true that cookies can't be set with 4xx responses?
RFC 6265 states that those cookies MUST be accepted:
Origin servers MAY send a Set-Cookie response header with any response. User agents MAY ignore Set-Cookie headers contained in responses with 100-level status codes but MUST process Set-Cookie headers contained in other responses (including responses with 400- and 500-level status codes). An origin server can include multiple Set-Cookie header fields in a single response. The presence of a Cookie or a Set-Cookie header field does not preclude HTTP caches from storing and reusing a response.