Quick Guide: Securing Node.js APIs with JWT
2 min read
Table of contents
Secure Node.js APIs with JWT: A Quick Guide
Hello, community. ๐ Let's look at a quick and effective way to secure your Node.js APIs with JSON Web Tokens (JWT). ๐๐ป
1. Install Dependencies: ๐ฆ
Start by installing jsonwebtoken
:
npm install jsonwebtoken
2. Use JWT in Authentication: ๐ฆ
When a user logs in, create JWT tokens with user info:
const jwt = require('jsonwebtoken');
// ... Your login logic
const user = { id: userId, username: 'example' };
const accessToken = jwt.sign(user, 'your-secret-key', { expiresIn: '1h' });
const refreshToken = jwt.sign(user, 'refresh-secret-key', { expiresIn: '7d' });
3. Include JWT in API Requests:
For protected routes, add the tokens to your API requests:
// Example using Axios
axios.get('/api/protected-route', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
4. Middleware for Authorization:
Create middleware to verify the access token before accessing protected routes:
const jwt = require('jsonwebtoken');
const authenticateUser = (req, res, next) => {
const token = req.header('Authorization');
if (!token) {
return res.status(401).json({ message: 'Unauthorized' });
}
try {
const decoded = jwt.verify(token, 'your-secret-key');
req.user = decoded;
next();
} catch (error) {
return res.status(401).json({ message: 'Invalid token' });
}
};
// Apply the middleware to your protected routes
app.get('/api/protected-route', authenticateUser, (req, res) => {
// Accessible only with a valid access token
res.json({ message: 'Welcome to the protected route!' });
});
5. Token Expiration and Refresh:
Set expiration for access tokens and consider implementing a refresh token mechanism for enhanced security.
MongoDB User Schema:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
// ... Other user properties
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Conclusion: ๐
Securing your Node.js APIs with JWT is a quick and reliable solution. Tokens should be kept secure, keys handled with caution, and security measures reviewed on a regular basis.
Any questions or thoughts? Leave them in the comments! Happy coding!
#NodeJS, Security, APIs, JWT, Web Development, Authentication