RESTful API – Should Cookies Be Used?

restweb servicesweb-applications

I'm specifically interested in how users perform authorized / authenticated operations on a web API.

Are authentication cookies compatible with the REST philosophy, and why?

Best Answer

An ideal ReSTful service allows clients (which may not be in-browser) to perform any needed task in one request; because the full state needed to do that is held by the client, not the server. Since the client has full control of the state, it can create the state on its own (if that is legitimate), and only talk to the API to "get 'er done".

Requiring cookies can make that difficult. For clients besides browsers, managing cookies is a pretty big inconvenience compared to query params, plain request headers or the request body. On the other hand, In browser, using cookies can make lots of things much simpler.

So an API might first look in the Authorization header for the authentication data it needs, since that's probably the place where non-browser clients will prefer to put it, but to simplify and streamline browser-based clients, it might also check for a session cookie for server side log in, but only if the regular Authorization header was missing.

Another example might be a complex request that normally requires lots of parameters set. A non interactive client would have no trouble jamming all of that data into one request, but a HTML form based interface might prefer to break the request into several pages (something like a set of 'wizard' pages) so that users aren't presented with options that are not applicable based on previous selections. All of the intermediate pages could store the values in client side cookies, so that only the very last page, where the user actually submits the request, has any server side effect at all. The API could look for the needed attributes in the request body, and fall back to looking at cookies if the needed parameters weren't there.

Edit: in RE to @Konrad's comment below:

Tokens in comparison are harder to implement especially because you can't easily invalidate the token without storing them somewhere.

er... you are validating the cookies on the server side, right? Just because you told the browser to discard a cookie after 24 hours doesn't mean it will. That cookie could be saved by a highly technical user and reused long after it has "expired".

If you don't want to store session data on the server side, you should store it in the token (cookie or otherwise). A self contained auth token is sometimes called a Macaroon. How this is passed between client and server (whether by cookie, as extra headers, or in the request entity itself) is totally independent of the authentication mechanism itself.