JSON Web Tokens (JWTs)

JSON web tokens are a type of access tokens that are widely used web applications. A JWT is based on JSON(JavaScript Object) format.
To ensure the integrity of the token, a JWT includes a signature.

Unlike a cookie which can easily be forged(neglecting exceptions), what makes a JWT hard to alter is the fact that it has a signature(that either uses a secret key/private key to ensure integrity)

How do JWTs work?

Just like cookies have name and value pairs, a JWT comprises :

Payload

A header is followed by the payload. Since JWTs are used in access control mechanisms, so the payload is such that it is relevant to the mechanism.
If the main purpose is to identify the user as an admin or any other non-admin user, the payload could be set as the one given below.

{access_type:"admin"}
When base64url encoded, this produces the following string : eyJhY2Nlc3NfdHlwZSI6ImFkbWluIn0

Signature

So, if the header and the payload are basee64url encoded can't they be easily changed?
Yes, they can be and this is what makes them insecure to use. But the third element in JWT makes them reliable and secure(to an extent, that we'll learn later) to use.
The third element of a JWT is its signature.

Remember from the header section that it tells what algorithm to use? Well it tells the application to encrypt the header and the payload with a key using the same algorithm.

signature = HMAC-SHA256(base64urlEncode(header) + '.' + base64urlEncode(payload), secret_key)
NOTE : I've used secret_key=learnjwt
signature=DnV2av0k-4PxoDRVLORqAA8cju8sZ8xAgq8tcV9oG7Q

JWT Token

For an application using JWT, you might see something as ,
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3NfdHlwZSI6ImFkbWluIn0.DnV2av0k-4PxoDRVLORqAA8cju8sZ8xAgq8tcV9oG7Q