Introduction to JSON Web Tokens (JWT)
JSON Web Tokens (JWT) are an open standard (RFC 7519) that define a compact and self-contained way 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 the HMAC algorithm) or a public/private key pair using RSA or ECDSA. This article explores the jsonwebtoken
library in Node.js, offering a thorough introduction to its functionalities and practical examples of usage.
Installation
npm install jsonwebtoken
APIs and Usage
1. Creating a Token
To create a token, you need to sign it with a secret or a private key. Here’s how to do it:
const jwt = require('jsonwebtoken');
const payload = {
id: '123abc',
role: 'admin'
};
const secret = 'mySecretKey';
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log('Generated Token:', token);
2. Verifying a Token
Verifying a token ensures its integrity and authenticity. Here’s an example:
jwt.verify(token, secret, (err, decoded) => {
if (err) {
console.error('Token verification failed:', err);
} else {
console.log('Decoded Payload:', decoded);
}
});
3. Decoding a Token Without Verification
To get the payload of a token without verifying it, use jwt.decode()
:
const decoded = jwt.decode(token);
console.log('Decoded Payload without verification:', decoded);
4. Asynchronous and Synchronous Signing and Verification
In addition to asynchronously signing and verifying tokens, you can do so synchronously:
// Synchronous signing
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
console.log('Generated Token:', token);
// Synchronous verifying
try {
const decoded = jwt.verify(token, secret);
console.log('Decoded Payload:', decoded);
} catch (err) {
console.error('Token verification failed:', err);
}
Sample Application
Below is an example of a basic Express application implementing JWT for securing routes:
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const secret = 'mySecretKey';
app.use(express.json());
// Middleware to protect routes
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.sendStatus(401);
jwt.verify(token, secret, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.post('/login', (req, res) => {
// Assume user is authenticated and get user info
const user = { id: req.body.id, role: req.body.role };
const token = jwt.sign(user, secret, { expiresIn: '1h' });
res.json({ token });
});
app.get('/protected', authenticateToken, (req, res) => {
res.json({ message: 'This is a protected route', user: req.user });
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
With this foundational knowledge, you can further explore JWTs to strengthen security in your applications.
Hash: 44701fc5b201f819a01da9d5f4f93c393c2f1100ccfef5f5f32cf16549e81c03