How to authenticate using the JSON Web Token
JSON Web Token(JWT) is a standard that defines a safe, compact, and self-contained way of transmitting information between a client and a server in the form of a JSON object. A JWT can either be signed (JWS), encrypted (JWE), or both.
How JWT authentication works
Here is the basic flow of JWT authentication:
The client sends a request to the server with user credentials.
If the credentials are valid, the server generates a signed JWT for the client.
The server sends the token back to the client, and stores it in the browser.
The client sends the token back to the server for every subsequent request.
The server validates the token. If it is valid, it then grants access to the client.
Signing tokens
There are two mechanisms to sign a token:
Symmetric signatures
Asymmetric signatures
Let's discuss them in detail:
Symmetric signatures
In symmetric signatures, the JWT is signed using a secret key. This type of signature occurs when there is only one server that signs and validates the token. The same secret key generates and validates the token. The token is signed using
Asymmetric signatures
Asymmetric signatures use a private-public key pair for signing. There is one server that has a private key. This server generates the tokens, signs them using the private key, and shares them with the client.
Now, the client can send this token to any application, and they can validate it using the public key. This signature is done using RSA. It is asymmetric encryption and a digital signature algorithm.
Note: Asymmetric signatures are suitable for distributed scenarios. Let's suppose there are multiple applications that need to validate the token. In this case, we can't share the secret key with them as it may get leaked.
Validating tokens
Let's now look at how a server validates a JWT. We know that a JWT has three parts: a header, a payload, and a signature.
When a server receives a token, it fetches the header and payload from that token. It then uses the secret or public key (in the case of asymmetric signing) to generate the signature from the header and payload.
If the generated signature matches the signature provided in the JWT, it is considered valid.
Note: It is not sufficient to just validate the signature of the token. There are a few other security properties we must validate as well, but those are beyond the scope of this Answer.
Free Resources