10.Json Web Token

Json Web Token (JWK)

Json web tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which will be perfect for the restful APIs as restful APIs should always be stateless.

A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data.

How Json Web Token (JWK) authentication works

Assuming, we have registered user in database.

For Login

  1. Client - User starts to POST to request to login with email and password.
  2. then the application checks if the user exists and if the password is correct. If so, a unique JWT for only that user will be created using a sceret string stored on the server.
  3. then the server sends the JWT back to the client which will be stored either in cookie or local storage.

Thus, user will be authenticated and logged into the application without leaving any state on the server. In this case, server doesn't know which user logged in, only the user knows (as he have a valid unique Json web token).
Therefore, this process is completely stateless.

For access

  1. When user want to access a protected route like his profile, he sends a JWT along with the request.
  2. Once the request hits the server, our app will verify if the JWT is actually valid (if the user really is who he claims to be)
  3. If the token is valid, the requested data will be sent back to the client. If the token is not valid, a message will be sent like you are not allowed to access the resource.