Understanding JSON Web Tokens
Understanding JSON Web Tokens
JSON Web Tokens (JWTs) are an open, industry standard RFC 7519 method for representing claims securely between two parties.
What is a JWT?
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.
JWT Structure
A JWT consists of three parts separated by dots (.), which are:
- Header
- Payload
- Signature
Therefore, a JWT typically looks like the following:
xxxxx.yyyyy.zzzzz
Let's break down the different parts.
Header
The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.
For example:
{
"alg": "HS256",
"typ": "JWT"
}
Payload
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data.
There are three types of claims: registered, public, and private claims.
Example payload:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"iat": 1516239022
}
Signature
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
When to Use JWTs
Here are some scenarios where JSON Web Tokens are useful:
-
Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.
-
Information Exchange: JWTs are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are.
Security Considerations
- Always use HTTPS to transmit JWTs
- Keep tokens short-lived
- Don't store sensitive data in the payload
- Use strong signing algorithms
- Validate all tokens on the server side
JWTs are a powerful tool for modern web applications, but they must be implemented correctly to ensure security.