JWT stands for JSON web token. It is a stateless solution for authentication. There is no need to store any session state on the server. Which is perfect for restful API as Restful API must always be stateless.
JWT gets a lot of hate from the crypto community because of algorithm selection and a sentiment that it is a way to avoid server-side code or protocol such as OAuth and OpenID connect.
But as a beginner, it doesn't actually matter which authentication we are using, but we should at least try to understand how it works.
So let's see how authentication works with JWT:
- User starts with POST request with username and password.
- Application checks if username and password is correct and then generates unique JWT only for that user.
Server sends JWT to the client, which it stores either in cookie or in local storage.
So, just like this user is logged into our application without leaving any state on the server. So, the server doesn't know which user is logged in but user itself knows that it is logged in. Because he has valid JWT.
So every time a user wants to access protected routes he has to sends his JWT along with the request. It is just like showing passport to enter into a new country.
- Then application verifies if the JWT is actually valid.
- If token is valid then data is send to the user.
Note:- Communication must happens over HTTPS in order to prevent anyone getting access to the password or JWT.
This is all you need to know to use JWT for authentication.
Now. let's see how JWT itself actually works:
It is an encoding string made up of 3 parts:-
- Header:- It is an metadata about token itself.
- Payload:- It is any data that we want to encode into the token. the bigger the data the longer JWT.
- Signature:- Previous 2 parts are encoded but not encrypted. So any one can decode and read them. So we can't store sensitive information here. The signature is create using the header,payload and the secret that is saved in the server. And the process is called signing the JWT.
Verifying:- Once the server receive JWT, it needs to verify if the user is really who he claims to be. It will verify that no one changed header and the payload of JWT.
Once JWT is received. The verification will receive it's header and payload and together with it secret that is stored in the server. It will create a test signature. The original signature that was created is still in JWT. So, we just need to compare original signature with the test signature. If they are the same then it means that payload and header has not been modified. Them we can authenticate the user and no manipulation has been done.
So, signing and verifying is what makes JWT so simple yet extremely powerful.