Understanding the concept of Logging In using JSON Web Token(JWT)

What is JWT?
JSON Web Token or JWT is a stateless solution for authentication. Being stateless eliminates the need for the server to maintain a session or store state information, thus providing better security and making it easier to scale and maintain the application. Also, the token can get revoked or expire without having to update the server's state. Additionally, there is no risk of a user's session getting stolen or hijacked.

Now that we know what JWT is, it is time to understand the concept of how JWT works when a registered user wants to make a login request.

Let's look at an example of a token getting generated while a user login.

Explanation of the process:

  1. The client sends a post request with the username and password.

  2. Then the server checks if the provided username and password are correct. If it is then a unique valid token is created.

  3. This token gets sent back to the client.
    Example token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzZTEzODk4ODNlOTI1NThjMGZjMzhjNSIsImlhdCI6MTY3NTcwNDQ3MywiZXhwIjoxNjgzNDgwNDczfQ.C2CyVUxe7PAZRPy4ZQD8M4WJhhC_ZgZ8Bc9K7BRrxhQ"

  4. Then the token gets stored in a cookie or local storage making the process stateless.

After that, the user gets logged in to the application without leaving any state on the server. The server does not know which users are actually logged in. But the user knows that he's logged in because the user has a valid JWToken.

JWT is perfect for REST APIs since restful APIs should always be stateless. Another common use alternative is to store users' log-in information on the server using sessions but that does not follow the principle that says that restful APIs should be stateless.

TLDR: Client sends info --> If verified sends back token -->The token is stored in local storage or a cookie of the client. The whole process is stateless.

Hope this article helped someone.

Happy Hacking!