JWT Structure
A JWT token consists of three parts separated by dots (.):
header.payload.signature
1. Header
The header typically consists of two parts: the type of token (JWT) and the signing algorithm being used.
{\n "alg": "HS256",\n "typ": "JWT"\n}2. Payload
The payload contains the claims. Claims are statements about an entity (typically the user) and additional data. There are three types of claims:
- Registered claims: Predefined claims like iss (issuer), exp (expiration), sub (subject), aud (audience)
- Public claims: Custom claims that should be defined in the IANA JSON Web Token Registry
- Private claims: Custom claims created to share information between parties
{\n "sub": "1234567890",\n "name": "John Doe",\n "iat": 1516239022,\n "exp": 1516242622\n}3. Signature
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way. To create the signature, you take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
HMACSHA256(\n base64UrlEncode(header) + "." +\n base64UrlEncode(payload),\n secret\n)
Signature Verification
To verify a JWT signature:
- Recreate the signature using the header and payload from the token along with the secret/key
- Compare the recreated signature with the signature part of the token
- If they match, the token is valid and untampered
Claim Validation
Common claims to validate include:
- exp (Expiration Time): Ensure the token has not expired
- iat (Issued At): Check if the token was issued in a valid timeframe
- nbf (Not Before): Ensure the token is not used before a certain time
Leave a Comment
We'd love to hear from you