What is a JWT?
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and information exchange.
JWT Structure
A JWT consists of three parts separated by dots:
xxxxx.yyyyy.zzzzz
Header.Payload.Signature
1. Header
Contains the token type and signing algorithm:
{
"alg": "HS256",
"typ": "JWT"
}
2. Payload
Contains the claims (statements about the user and metadata):
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"iat": 1516239022,
"exp": 1516242622
}
3. Signature
Verifies the token hasn't been tampered with:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Standard Claims
iss | Issuer | Who created the token |
|---|
sub | Subject | Who the token is about |
|---|
aud | Audience | Who the token is for |
|---|
exp | Expiration | When the token expires |
|---|
iat | Issued At | When the token was created |
|---|
nbf | Not Before | Token not valid before this time |
|---|
Why Use JWTs?
- Stateless: Server doesn't need to store session data
- Scalable: Works across multiple servers
- Mobile-friendly: Easy to use in native apps
- Cross-domain: Can be used across different domains