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 do I download a zip file using Express.js?
- How do I use adm-zip with Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I find Express.js tutorials on YouTube?
- How can I use Express.js to develop a web application?
- How can I use Express.js to make an XHR request?
- How can I use Express.js to prevent XSS attacks?
- How can I create and use models in Express.js?
- How do I use Yarn to add Express.js to my project?
- How do I use Express.js to handle x-www-form-urlencoded data?
See more codes...