Last active
November 13, 2020 01:01
-
-
Save ArthurMbraga/54af095017b265c16d6a3b3578817d5e to your computer and use it in GitHub Desktop.
Token JWT authentication middleware for NodeJs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jwt = require('jsonwebtoken'); | |
module.exports = { | |
async authenticateToken(request, response, next) { | |
const authHeader = request.headers['authorization'] | |
const [scheme, token] = authHeader && authHeader.split(' '); | |
if (token === null) return response.status(401).json({ error: 'No token provided' }); | |
if (!/^Bearer$/i.test(scheme)) | |
return response.status(401).json({ error: 'Token badformatted' }); | |
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err) => { | |
if (err) return response.status(403).json({ error: 'Invalid authorization token' }); | |
request.session = data; | |
next(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment