Authentication via API — the blueprintDmytro HuzBlockedUnblockFollowFollowingMay 11This article will present a general approach to implementing authentication via the API.
There will be no implementation of this approach by using particular languages and technologies.
If you want to read about the implementation of authentication via API using any language or framework, let me know by writing in the comments.
The main components and their interaction.
Obviously, if the task is to implement authentication via API, then we have at least two components — a server and a client.
The main difficulty in server and client interaction through the API is that the server does not have direct access to the client’s state and can’t share information between requests.
Unlike how it works for standard authentication, where we store some information between requests in the browser storage and can authenticate the user via direct access to it from the server.
Thus, in the implementation of authentication through the API, we have to authenticate the user with every request to the server and verify its validity.
To implement this approach, we need:- the client that sends HTTP / s requests to the server;- the server that handles HTTPs requests;- storage that we will use to store customer information.
This can be SQL DB, NoSQL DB, hash table, file or whatever.
AuthorizationThe first request in client-server communication via the API should be an authorization request.
it looks like this:1) The client sends the username and password to the server.
2) The server checks the login and password matches in the storage.
3) If the data is valid, the server generates a token.
4) Store the user ID/login and token in the repository, as well as the lifetime of this token.
5) send a token in the HTTP/s response to the client.
AuthenticationThus, the client has a unique token by which the server recognizes it.
Next, we need to ensure that we send this token to the server with every request.
It works in that way:1) Get a token from the server.
2) Save it to the storage of the browser, for a period corresponding to its lifetime, which we indicated in the database.
3) To each request to the server add a token that we saved in the local storage of the browser.
The most common is to use the token in the Authorization: Basic <token> and Authorization: Bearer <token> headers.
Check the token on the serverWhen a user sends a request to the server with an attempt to make an operation accessible only to an authorized user.
We have to check if his token exists if it is valid and to whom it belongs.
The algorithm is as follows:1) Get a token from the request headers.
2) Check if it exists in the storage and if its life span is valid.
3) get the ID of the user who is responsible for it.
Thus, using such a simple algorithm, you can independently and quickly implement authentication through the API.
Will be happy to answer any questions in the comments.