Day 15: JWT Authentication
How it’s Done Now: JWT-Based Authorization
A user makes a POST request with their credentials, which is sent to the server, just like session-based authentication. Instead of storing information on the server inside session memory, the server creates a JSON Web Token (JWT), which it encodes, serializes, and signs with its own secret key. A JWT consists of three parts: the header, the payload, and the signature
-
Header: This contains metadata about the token, such as the algorithm used for signing (e.g., HS256) and the type of token (e.g., JWT).
{ "alg": "HS256", "typ": "JWT" } -
Payload: This contains the claims, which are pieces of information about the user or token, like the user ID, role, and token expiration time.
{ "userId": "12345", "role": "admin", "exp": 1714737600 }
These are Base64Url-encoded to form the first two parts of the token:
Header (encoded): eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Payload (encoded): eyJ1c2VySWQiOiIxMjM0NSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTcxNDczNzYwMH0
The Signature is then generated by hashing the encoded header and payload together using the secret key:
Signature: HMAC_SHA256(header.payload, secretKey)
The final JWT looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTcxNDczNzYwMH0.L4KthgDhnAw_9mGh9qtx3LdCGXdpofgJOUO7GtBxtR4
The server can later verify the token’s integrity by recalculating the signature using the header, payload, and its secret key, ensuring no tampering occurred.
So, in the session-based method the server had to do a lookup operation to find the user based on their session ID. In contrast, the JWT already stores the user information which means it’s stored on the client-side and won’t run into problems where one server has session info and others don’t.