JSON Web Token (JWT) is a standard for creating access tokens that can be easily verified by the server. In a Node.js application, you can use libraries like jsonwebtoken
to implement JWT authentication. Here's a step-by-step guide on how to implement JWT authentication in a Node.js application:
Install necessary packages: First, install the required npm packages by running the following commands in your terminal:
bashnpm install express jsonwebtoken body-parser
Set up your Node.js project:
Create a new Node.js project if you haven't already. You can do this by running npm init
and following the prompts.
Create an Express app: Create a basic Express application. Here's a simple example:
javascriptconst express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
const port = 3000;
app.use(bodyParser.json());
// Your routes will go here
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Implement JWT generation and verification functions: Create functions for generating and verifying JWT tokens. These functions will be used in your authentication middleware.
javascriptconst secretKey = 'your-secret-key'; // Replace with your own secret key
// Function to generate a JWT token
function generateToken(payload) {
return jwt.sign(payload, secretKey, { expiresIn: '1h' }); // You can adjust the expiration time
}
// Function to verify a JWT token
function verifyToken(token) {
try {
return jwt.verify(token, secretKey);
} catch (error) {
return null;
}
}
module.exports = { generateToken, verifyToken };
Implement authentication middleware: Create a middleware function that checks the presence and validity of a JWT token in the incoming request.
javascriptconst { verifyToken } = require('./jwt-utils');
function authenticateToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ message: 'Unauthorized: Token not provided' });
}
const decodedToken = verifyToken(token);
if (!decodedToken) {
return res.status(403).json({ message: 'Forbidden: Invalid token' });
}
req.user = decodedToken; // Set the decoded token in the request object
next();
}
module.exports = authenticateToken;
Use the authentication middleware in your routes: Apply the authentication middleware to the routes that require authentication.
javascriptconst authenticateToken = require('./middleware/authenticateToken');
app.get('/protected-route', authenticateToken, (req, res) => {
res.json({ message: 'You have access to this protected route', user: req.user });
});
In this example, the /protected-route
route is protected by the authenticateToken
middleware. The middleware checks for a valid JWT token in the request header, and if the token is valid, it decodes the token and attaches the user information to the req.user
object.
Remember to replace the placeholder your-secret-key
with a secure secret key of your choice. Additionally, you may want to store sensitive information such as secret keys in environment variables for better security.