Authentication and Authorization Using JWT With Node.js
To implement authentication and authorization using JSON Web Tokens (JWT) in Express, you can follow these steps:
Step 1: Install Dependencies First, you need to install the necessary dependencies. Open your terminal and navigate to your Express project directory, then run the following command:
npm install jsonwebtoken
Step 2: Set up JWT Middleware
Create a new file called jwtMiddleware.js
and add the following code:
const jwt = require('jsonwebtoken');
function verifyToken(req, res, next) {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ message: 'No token provided' });
}
jwt.verify(token, 'your_secret_key', (err, decoded) => {
if (err) {
return res.status(403).json({ message: 'Failed to authenticate token' });
}
req.userId = decoded.userId;
next();
});
}
module.exports = verifyToken;
Make sure to replace 'your_secret_key'
with your own secret key. This middleware function will verify the token and attach the decoded userId
to the request object (req.userId
) if the token is valid.
Step 3: Create Authentication and Authorization Routes In your Express application, create routes for authentication and authorization. For example, you can have routes for registering, logging in, and accessing protected resources. Here’s an example:
const express = require('express');
const jwtMiddleware = require('./jwtMiddleware');
const app = express();
// Authentication route
app.post('/login', (req, res) => {
// Perform authentication logic
// Assuming the user is authenticated successfully
const userId = 123; // Get the user ID from your authentication logic
// Create and sign the token
const token = jwt.sign({ userId }, 'your_secret_key');
// Send the token back to the client
res.json({ token });
});
// Protected route
app.get('/protected', jwtMiddleware, (req, res) => {
// Access the user ID from the request object
const userId = req.userId;
// Use the user ID to fetch protected resources
// Return the resources to the client
res.json({ userId, data: 'Protected data' });
});
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000');
});
In the /login
route, you perform the authentication logic, generate a token using jwt.sign()
, and send the token back to the client.
In the /protected
route, you add the jwtMiddleware
as middleware. This middleware will verify the token and attach the userId
to the request object. If the token is invalid or missing, the middleware will return an appropriate response.
Step 4: Test the Authentication and Authorization Start your Express server (node app.js
or npm start
) and use a tool like Postman or curl to test the routes.
- Send a POST request to
/login
with any necessary credentials. You should receive a token in the response. - Copy the token from the response.
- Send a GET request to
/protected
and include the token in theAuthorization
header asBearer <token>
. You should receive a response with the protected data and the user ID.
That’s it! You’ve implemented authentication and authorization using JWT in Express. Remember to handle token expiration, token refresh, and securely storing the secret key in a production environment.