I've been working with JWT in mostly all of the projects for the past 5 years, I myself had set up an authentication endpoint using JWT for a personal project from scratch and yet, sometimes I fail to answer how JWT works in interviews.
The objective of this post is basically to create a simple strategy to fix this concept in our heads so when we get to an interview and they ask around that, we know how to counter-punch.
It should be simple, so let's stop with the useless chatty chat and go to what really matters.
THE JWT
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
That's how a JWT token would look like, each dot represents a divisor in the structure.
1. Structure
header.payload.signature
Header
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
The header usually stores the algorithm and the token type.
The algorithm stands for the type of algorithm that will be used to encode the token, usually we use HS256.
Payload
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
The payload usually contains something like:
{"iat": timestamp, "iss": string, "exp": timestamp, "userId": string, "userRole": boolean}
User identification (e.g.: userId, userRole)
Expiry
IssuedAt (iat): Represents the token creation date.
Issuer: (iss): Servername whom issued the token.
Expiry: (exp): Token expiration time.
Signature
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
The signature is compound by creating a hash using HMACSHA256 algorithm with the given input:
HMACSHA256(
base64(header),
base64(payload),
base64(key)
) = Signature.
Simple as that, we have an output which is the Encoded JWT token, it now can only be validated by servers who have the key and where the key is matchable with the token.
Top comments (0)