Bearer token
Wed May 29 2024 07:45:07 GMT+0000 (Coordinated Universal Time)
Saved by
@sid_balar
var jwt = require('jsonwebtoken');
function auth(req, res, next) {
// Extract the token from the Authorization header
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).send('Authorization header is missing');
}
// Ensure the token is a Bearer token
const tokenParts = authHeader.split(' ');
if (tokenParts.length !== 2 || tokenParts[0] !== 'Bearer') {
return res.status(401).send('Invalid Authorization header format');
}
const token = tokenParts[1];
// Verify the token
jwt.verify(token, 'sid', function(err, decoded) {
if (err) {
return res.status(401).send('Failed to authenticate token');
} else {
// Optionally, you can attach the decoded information to the request object
req.user = decoded;
next();
}
});
}
module.exports = auth;
content_copyCOPY
Comments