expressjsHow do I set up Express.js JWT authentication?
To set up Express.js JWT authentication, you need to install the jsonwebtoken package first, then create a secret key to sign the token, and then create a middleware to verify the token.
- Install the jsonwebtoken package:
npm install jsonwebtoken
- Create a secret key to sign the token:
const secret = 'supersecret';
- Create a middleware to verify the token:
const verifyToken = (req, res, next) => {
const token = req.headers['x-access-token'];
if (!token) {
return res.status(403).send({
auth: false,
message: 'No token provided.'
});
}
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(500).send({
auth: false,
message: 'Failed to authenticate token.'
});
}
// If everything is good, save to request for use in other routes
req.userId = decoded.id;
next();
});
};
- Use the middleware in the routes that need authentication:
app.get('/protected', verifyToken, (req, res) => {
res.send('Access granted.');
});
For more details, please refer to this guide.
Code explanation
**
- Install the jsonwebtoken package:
npm install jsonwebtoken
This command installs the jsonwebtoken package to your project.
- Create a secret key to sign the token:
const secret = 'supersecret';
This code creates a secret key to sign the token.
- Create a middleware to verify the token:
const verifyToken = (req, res, next) => {
const token = req.headers['x-access-token'];
if (!token) {
return res.status(403).send({
auth: false,
message: 'No token provided.'
});
}
jwt.verify(token, secret, (err, decoded) => {
if (err) {
return res.status(500).send({
auth: false,
message: 'Failed to authenticate token.'
});
}
// If everything is good, save to request for use in other routes
req.userId = decoded.id;
next();
});
};
This code creates a middleware to verify the token. It first checks if the token exists in the request header, and then verifies the token with the secret key. If the token is verified, it will save the decoded token to the request for use in other routes.
- Use the middleware in the routes that need authentication:
app.get('/protected', verifyToken, (req, res) => {
res.send('Access granted.');
});
This code uses the middleware in the routes that need authentication. When the token is verified, it will send a response of "Access granted".
More of Expressjs
- How can I disable the X-Powered-By header in Express.js?
- How do I use Express.js to parse YAML files?
- How do I use an Express.js logger?
- How do I use Express.js and Yarn together in a software development project?
- How can I set up X-Frame-Options in ExpressJS?
- How can I use the x-forwarded-for header in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js and Babel together to develop a web application?
- How do I set the time zone in Express.js?
- How can I use Express.js to prevent XSS attacks?
See more codes...