What is a JWT? Complete Guide to JSON Web Tokens
What is a JSON Web Token (JWT)?
A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. JWTs are commonly used for authentication and information exchange in web applications.
The Three Parts of a JWT
Every JWT consists of three parts separated by dots (.):
1. Header
The header typically contains two pieces of information:
- alg: The signing algorithm (e.g., HS256, RS256)
- typ: The token type, which is JWT
Example header:
``json
{
"alg": "HS256",
"typ": "JWT"
}
`
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 defined in the IANA JSON Web Token Registry
- Private claims: Custom claims created to share information between parties
Example payload:
`json
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022,
"exp": 1516242622
}
``
3. Signature
The signature is used to verify the token hasn't been altered. It's created by taking the encoded header, encoded payload, a secret, and the algorithm specified in the header.
How JWT Authentication Works
Benefits of Using JWT
- Stateless: No need to store session data on the server
- Portable: Works across different domains and services
- Compact: Small size makes it efficient for transmission
- Self-contained: Contains all necessary user information
When to Use JWT
JWTs are ideal for:
- Single sign-on (SSO) implementations
- API authentication
- Information exchange between services
- Mobile app authentication