A Comprehensive Guide to understanding JWT Tokens
Overview
JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is commonly used for authentication and authorization in web applications. In this blog, we'll explore what JWT tokens are, how they work, and how to use them effectively in your applications.
What is a JWT?
A JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Structure of a JWT
A JWT is made up of three parts, separated by dots (.
):
- Header
- Payload
- Signature
{
"header": {
"alg": "Algorithm used to sign the token",
"typ": "Type of token, usually JWT"
},
"payload": {
"sub": "Subject of the token, typically the user ID",
"name": "Name of the user",
"iat": "Issued At time, the time at which the token was issued",
"exp": "Expiration time, the time at which the token expires",
"iss": "Issuer, the entity that issued the token",
"aud": "Audience, the recipients that the token is intended for",
"nbf": "Not Before, the time before which the token must not be accepted for processing",
"jti": "JWT ID, a unique identifier for the token",
"email": "Email of the user",
"roles": "Roles assigned to the user"
},
"signature": "Signature to verify the authenticity of the token"
}
1. 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.
{
"alg": "HS256",
"typ": "JWT"
}
This JSON is then Base64Url encoded to form the first part of the 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 which are not mandatory but recommended, such as
iss
(issuer),exp
(expiration time),sub
(subject), andaud
(audience). - Public claims: Claims that can be defined at will by those using JWTs. To avoid collisions, these should be defined in the IANA JSON Web Token Registry or as a URI.
- Private claims: Custom claims created to share information between parties that agree on using them.
Example of a payload:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
This JSON is then Base64Url encoded to form the second part of the JWT.
3. Signature
To create the signature part, you have to take the encoded header, the encoded payload, a secret, and 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)
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.
Putting it all together
The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments, such as in an HTTP header.
xxxxx.yyyyy.zzzzz
How JWTs Work
- Authentication: When the user successfully logs in using their credentials, a JWT will be returned.
- Storage: The client usually stores the token in local storage or cookies.
- Authorization: On every request to the server, the client sends the JWT in the HTTP header.
- Validation: The server verifies the token's signature and extracts the claims to process the request.
Using JWT in Your Application
Setting Up
First, install the necessary libraries. For a Node.js application, you can use the jsonwebtoken
library:
npm install jsonwebtoken
Generating a Token
Here's how you can generate a token in Node.js:
const jwt = require('jsonwebtoken');
const secretKey = 'your-256-bit-secret';
const payload = {
sub: '1234567890',
name: 'John Doe',
admin: true
};
const token = jwt.sign(payload, secretKey, { algorithm: 'HS256', expiresIn: '1h' });
console.log(token);
Verifying a Token
To verify a token, you can use the verify
method provided by jsonwebtoken
:
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
console.log('Token is not valid:', err);
} else {
console.log('Decoded payload:', decoded);
}
});
Middleware for Token Validation
In an Express.js application, you can create a middleware to protect your routes:
const jwt = require('jsonwebtoken');
const secretKey = 'your-256-bit-secret';
const authenticateJWT = (req, res, next) => {
const token = req.header('Authorization')?.split(' ')[1];
if (token) {
jwt.verify(token, secretKey, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
};
module.exports = authenticateJWT;
Use the middleware in your routes:
const express = require('express');
const app = express();
const authenticateJWT = require('./authenticateJWT');
app.get('/protected', authenticateJWT, (req, res) => {
res.json({ message: 'You have access to this protected route', user: req.user });
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Best Practices
- Keep it secret, keep it safe: The signing key should be stored securely.
- Set an expiration: Always set an expiration for your JWTs.
- Avoid storing sensitive data: Do not store sensitive data in the JWT payload as it can be decoded easily.
- Use HTTPS: Always use HTTPS to ensure tokens are sent securely.
Conclusion
JWT tokens are a powerful tool for authentication and authorization in web applications. They are easy to use and provide a secure way to transmit information between parties. By understanding how JWTs work and implementing them correctly, you can enhance the security and efficiency of your web applications. Happy coding!
Related Articles
CASL Ability Based Http Client to secure NextJS server actions
Explore how to use the AbilityBasedHttpClient class to integrate access control into your API requests using CASL and TypeScript.
08/10/2024
How and When to use AWS Parameters Store
How to Use Parameter Store in Amplify, Lambda, and Node.js Applications
12/08/2024
Why you might choose AWS Parameter Store over AWS Secrets Manager
When deciding between AWS Systems Manager Parameter Store and AWS Secrets Manager, it's important to consider the nature of the data you're storing
12/08/2024