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;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter