Understanding JWT (JSON Web Tokens)
1. What are JWTs used for?
Authentication vs Authorisation
Authentication is the process of taking in usernames and passwords to verify the identity of a user/service aka “login”, while Authorisation determines if a certain user has access rights to a resource. Additionally, Authorisation also needs to ensure that the user that is logged-in is the same user that is accessing the resource.
In this case, JWT is used for Authorisation.
Session ID vs JWTs
Traditionally, authorisation is implemented with the use of session cookies:
- Authentication — During login, server associates user logging in with a session ID. Session ID is stored in the server. Session ID is returned to the client which is stored as a cookie
- Authorisation —Session ID is included in subsequent client requests. Server checks session ID against stored keys to ensure that requesting user has access rights.

In the case of JWTs:
- Authentication — During login, server creates a JWT with jwt_secret and user_id as inputs. JWT is returned to the client.
- Authorisation — JWT is included in subsequent client requests. Server verifies JWT and obtains user_id. Checks if user has access rights.

As such, the main advantage JWTs have over the traditional session approach is that no information is stored in the server, as user information is stored within the JWT itself.
2. How does JWT work?

Creating JWTs
JWTs consists of 3 parts:
- Header — contains the
hash_algorithm
- Payload — contains the user info and jwt expiry details
- Signature — used for JWT verification (explained below)
Creating a signature:
signature = hash_algorithm(encoded(header) + "." + encoded(payload), jwt_secret)
jwt_secret is stored in the server
Creating a jwt:
jwt = encoded(header) + "." encoded(payload) + "." + signature
To “sign” a JWT means to create a signature that can only be re-created with the jwt_secret, appending the signature to the token
Verifying JWTs
In order to verify an incoming JWT, the server attempts to re-create the signature with the JWT’s header and JWT’s payload. The JWT is considered valid if the generated signature matches the incoming JWT’s signature.
3. Key takeaways
- JWT is used for Authorisation of requests
- JWT does not require servers to store any information
- JWT = header.payload.signature
- Signing a JWT = creating a JWT signature with the hash_algorithm
- Verifying a JWT = generated signature matches incoming JWT signature