How does authentication work in a stateless Restful environment?

Asked

Viewed 1,582 times

5

My question is this::

Imagine 3 Tomcat servers (S1,s2,S3) and all 3 servers connect to a single sgbd server (s_bd1).

The three Tomcat servers run an application that is of Restful and stateless nature, so they do not load the user’s session. here goes my two doubts:

1) How is it possible to authenticate the user after the login screen persists between future requests since it can navigate between the 3 servers transparently? (e.g. an inclusion request is sent to S1 and an update request sent to s2..)

2) How s2 will recognize the user if their login was done in S1 and the environment is stateless?

  • 2

    As far as I know, stateless means it is not maintained state on the server; the customer may have been (and as pointed out by sergiopereira, that state may be - but not necessarily will be - in a cookie).

1 answer

7

When it comes to 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.

Thus, the most common is to use the header Authorization with its variations Basic, Digest or Bearer.

A very popular option is to use Oauth with Bearer (Bearer Token). The header looks something like this (it follows pseudo-code):

string token = "tokenRecebidoViaLoginOAuth..provavelmente_bem_longo";
string authHeader = "Bearer " + base64Encode(token);
request.headers["Authorization"] = authHeader;

If you choose to Basic you can either use your web server to verify credentials or implement it 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 this header travels safely.

These aren’t the only ways to do it, but I see them in many of the Restful Apis I use and almost all of the Restful Apis I’ve 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.