In the case of RESTful, the same mechanisms used in HTTP apply. On the other hand, although many web applications use cookies, it would be strange to use them in an API.
In this way, the most common is to use the Authorization
header with its Basic
, Digest
or Bearer
variations.
A very popular option is to use OAuth with Bearer
(Bearer Token). The header looks something like this (pseudo-code follows):
string token = "tokenRecebidoViaLoginOAuth..provavelmente_bem_longo";
string authHeader = "Bearer " + base64Encode(token);
request.headers["Authorization"] = authHeader;
If you choose Basic
you can either use your web server to check the credentials or implement this yourself. The format is as follows:
string credenciais = "nome-de-usuario:senha";
string authHeader = "Basic " + base64Encode(credenciais);
request.headers["Authorization"] = authHeader;
In both cases, use HTTPS to ensure that this header will safely travel.
These are not the only ways to do this, but I see them in many of the RESTful APIs I use and in almost all of them I have implemented as well. I would personally recommend OAuth, especially if you are thinking of making this API available for a commercial system.
A major exception among the APIs I use are the Amazon APIs (AWS). AWS uses a form of digital signature on each request.