This content originally appeared on DEV Community and was authored by Softden 2005
JSON Web Tokens (JWT) are 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.
1. What is JWT?
JWT is a compact, URL-safe means of representing claims to be transferred between two parties. The token consists of three parts:
- Header
- Payload
- Signature
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
This token consists of:
-
Header:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
-
Payload:
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
-
Signature:
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
2. Components of JWT
a. Header
The header typically consists of two parts: the type of the token (i.e., JWT) and the signing algorithm being used, such as HMAC SHA256 or RSA.
Example:
{
"alg": "HS256",
"typ": "JWT"
}
This JSON is then Base64Url encoded to form the first part of the JWT.
b. 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), andaud
(audience). - Public claims: Claims created to be shared publicly.
- Private claims: Custom claims created to share information between parties that agree to use them.
Example:
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
This is also Base64Url encoded to form the second part of the JWT.
c. 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.
Example using HMAC SHA256:
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.
3. How JWT Works
- User Login: When a user logs in, the server authenticates the user and generates a JWT, signing it with a secret key.
- Client Stores JWT: The client stores this JWT (typically in localStorage or a cookie).
-
Client Sends JWT: The client sends the JWT in the
Authorization
header of future requests. - Server Verifies JWT: The server verifies the token’s signature and extracts the claims.
4. JWT in Node.js
Let’s look at how you can implement JWT in a Node.js application using the jsonwebtoken
library.
Installation
npm install jsonwebtoken
Generating a Token
const jwt = require('jsonwebtoken');
// Generate a token
const token = jwt.sign({ id: 123, name: "John Doe" }, 'your-256-bit-secret', {
expiresIn: '1h' // expires in 1 hour
});
console.log(token);
Verifying a Token
jwt.verify(token, 'your-256-bit-secret', function(err, decoded) {
if (err) {
console.log('Token is not valid');
} else {
console.log('Decoded token:', decoded);
}
});
5. Example Use Case
Express Middleware for Authentication
You can create middleware to protect routes.
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const authenticateJWT = (req, res, next) => {
const token = req.header('Authorization');
if (!token) return res.status(401).send('Access Denied');
try {
const verified = jwt.verify(token, 'your-256-bit-secret');
req.user = verified;
next();
} catch (err) {
res.status(400).send('Invalid Token');
}
};
app.get('/protected', authenticateJWT, (req, res) => {
res.send('You are viewing protected content!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
6. Best Practices
- Keep your secret key safe: Store your keys securely, using environment variables or secret management tools.
- Use HTTPS: Always transmit JWTs over HTTPS to prevent interception.
-
Set appropriate expiration: Always set an expiration on your tokens using the
exp
claim.
Conclusion
JWTs provide a powerful way to authenticate users and transmit information securely between parties. By understanding the structure and usage of JWTs, you can implement robust authentication mechanisms in your applications.
This guide covered the basics of JWT, its structure, how it works, and practical implementation in a Node.js application.
This content originally appeared on DEV Community and was authored by Softden 2005