What is JWT?
A JSON Web Token is a tool that allows users to identify themselves to the server and perform their requests. It consists of three parts. These parts are Header, Payload, and Signature.
The header and payload are JSON objects encoded in Base64, whereas the signature is a derived form of the encoded header, payload, and a secret key stored on the server, unified and encrypted by an algorithm.
The header and payload are not hashes, they are clear text, encoded with Base64 encoding. The real reason behind this encoding is not to hide data, but to carry JSON objects in a safer, more reliable way.
So shortly, Base64 is not for hiding data, but forming data in a string format to carry around easier!
When a user authenticates to a server, the server creates a JWT and signs it with a secret. After that moment, the user doesn’t need to authenticate anymore. Because it will carry this JWT in their requests' header, so-called Authorization. After every request, the server will try to recreate the same JWT to validate user’s authenticity.
Header
The header part keeps the type of the Token and encryption algorithm to encrypt the secret key stored in the server.
Payload
Payload part keeps information or so-called claims such as ID, username, and the expiration date of this token. There can be more or less information at this part, this can be customized.
Signature
In this part encoded header, encoded payload and encoded secret key being merged and then encrypted by the algorithm which was given in header.
Validation
JSON Web Tokens are one way encrypted tokens, so they can’t be decrypted. Then, how to validate them?
The server, which keeps header, payload, and secret key, can create the exact same token which was created before and can check if those two tokens are identical or not.
Without knowing the secret key, malicious users can’t create identical JWT that created by the Server. The only way to hack the system is to generate that JWT again.