Why would a RESTful API send cookies with the API response?

Bozho picture Bozho · Jan 13, 2018 · Viewed 16.8k times · Source

The other day I got a strange warning in my client after sending requests to twitter:

2018-01-12 02:32:50,162 WARN o.a.h.c.p.ResponseProcessCookies:130 - Invalid cookie header: "set-cookie: guest_id=v1%3A151572431977858379; Expires=Sun, 12 Jan 2020 02:31:59 UTC; Path=/; Domain=.twitter.com". Invalid 'expires' attribute: Sun, 12 Jan 2020 02:31:59 UTC

The format is correct, so in the end it's a http client misconfiguration, but that leaves me with the question: why would a RESTful API send cookies?

These appear to be the tracking cookies of twitter, so what use are they in a RESTful context? Does twitter want to set the cookie if invoked through XMLHttpRequest (rather than server-side), or is it a generic "set cookie" filter that they've mistakenly applied to API endpoints as well?

The question is not just about twitter, but in general about RESTful APIs.

Below is an excerpt from the raw response:

Server:
    tsa_b
pragma:
    no-cache
cache-control:
    no-cache, no-store, must-revalidate, pre-check=0, post-check=0
x-connection-hash:
    24fd4a4b3d61e33b6b94080b710a1e61
x-xss-protection:
    1; mode=block; report=https://twitter.com/i/xss_report
x-content-type-options:
    nosniff
x-rate-limit-limit:
    900
expires:
    Tue, 31 Mar 1981 05:00:00 GMT
Date:
    Fri, 12 Jan 2018 17:45:03 GMT
set-cookie:
    personalization_id="v1_/3EYpbQnCe+vnjhnBUew=="; Expires=Sun, 12 Jan 2020 17:45:03 UTC; Path=/; Domain=.twitter.com
set-cookie:
    lang=en; Path=/
set-cookie:
    guest_id=v1%3A1515770330954116; Expires=Sun, 12 Jan 2020 17:45:03 UTC; Path=/; Domain=.twitter.com
x-rate-limit-reset:
    1515780003
content-disposition:
    attachment; filename=json.json

Answer

ggradnig picture ggradnig · Aug 24, 2018

A RESTful API may send cookies just like a regular Web Application that serves HTML. Cookies per se don't violate the REST policy, it's how they are used. For example, the server might want to have its client remember a certain state, so that it can provide this state when requesting another resource at a later point.

However, cookies should not be used by a REST API if they are meant to maintain a client session on the server, such as a Session Token. This would violate the statelessness of the REST endpoint, as the server is required to know the state of each client in order to provide them with the requested resources.

Now, you mentioned that your specific REST endpoint sets a tracking cookie. This might be perfectly valid, because the tracking id can be seen as a property of the client that should be persisted. This cookie is probably not required by the server in order for it to serve requested resources.

This might also relate to this question on StackExchange: Should Cookies be used in RESTful APIs?