In this lesson, you will learn how to deconstruct a JSON Web Token (JWT) into its three distinct components: the header, the payload, and the signature.
While session-based authentication stores user state on the server, JWTs take a stateless approach by embedding identity information directly into the token. A JWT is represented as a single string consisting of three Base64Url-encoded parts separated by periods (.): header.payload.signature.
1. The Header
The header typically consists of two parts: the token type (JWT) and the signing algorithm being used (such as HS256 or RS256).
{
"alg": "HS256",
"typ": "JWT"
}
2. The Payload
The payload contains the "claims." These are the statements about the user or the metadata of the token. You might store the user's userId, their role, or an expiration timestamp (exp). It is important to remember that because this part is only Base64 encoded, it is not encrypted. Never store sensitive information like passwords or personal identifiers here.
{
"sub": "1234567890",
"name": "Jane Doe",
"iat": 1516239022
}
3. The Signature
The signature is the secret sauce of the JWT. It is created by taking the encoded header, the encoded payload, a secret key known only to the server, and the algorithm specified in the header.
The server calculates the signature like this:
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret)
Because the signature relies on a secret key that only your server possesses, it allows you to verify that the token was generated by you and that the payload has not been tampered with by the client or a malicious third party. If a user changes their userId in the payload, the signature will no longer match the token, and your server will reject it as invalid.
Key Takeaway: A JWT is a self-contained, cryptographically signed object made of a header, a payload, and a signature, allowing your Node.js server to verify user identity without needing to look up a session in the database.