What is JSON Web Token (JWT)
Posted on December 19, 2024 in Web Development
Summary of How JWT Authentication Works
JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.
The token consists of three parts separated by dots (.
): Header, Payload, and Signature.
-
Header: Contains metadata about the token, such as the type of token (JWT) and the signing algorithm being used (e.g., HMAC SHA256 or RSA).
json { "alg": "HS256", "typ": "JWT" }
-
Payload: Contains the claims, which are statements about an entity and additional data. There are three types of claims: registered, public, and private claims. Registered claims are predefined standard claims like
iss
(issuer),sub
(subject),aud
(audience), etc. Public claims are custom claims that can be defined by the token issuer. Private claims are custom claims not defined by the standards for JWTs.json { "sub": "1234567890", "name": "John Doe", "admin": true, "iat": 1516239022 }
-
Signature: Created by encoding the header and payload with a secret key (or private key) using the algorithm specified in the header. This ensures that the token has not been tampered with.
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret);
Diagram of JWT Authentication Flow
+-------------------+ +--------+ +------------------+ +-----------+
| | <------------- | | | | | |
| User Agent | Request | Server |-->| Verify Token |-->| Decode JWT|
| | -------------> | | | (Header, Payload)| | (claims) |
+-------------------+ +--------+ +------------------+ +-----------+
^ ^
|-----------------------------------------------------------|
|
JWT Issued
Steps:
- User Authentication: The user logs in and provides their credentials to the server.
- Server Validation: The server validates the user's credentials and generates a JWT containing claims about the user (e.g., user ID, role).
- Token Issuance: The server encodes the header, payload, and signs it with a secret key to create the token.
- Client Storage: The client stores the JWT (usually in localStorage or a cookie) for future use.
- Request with Token: On subsequent requests, the client includes the JWT in the Authorization header using the
Bearer
scheme. - Server Verification: The server receives the request and verifies the JWT's signature to ensure it hasn't been tampered with.
- Claim Decoding: If the token is valid, the server decodes the claims (header, payload) to retrieve user information and perform necessary operations based on the claims.
Links of Interest
- https://jwt.io/introduction
- RFC https://datatracker.ietf.org/doc/html/rfc7519