jwt token authentication node js code example
Example 1: jwt token example in node js
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization']
const token = authHeader && authHeader.split(' ')[1]
if (token == null) return res.sendStatus(401)
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET as string, (err: any, user: any) => {
console.log(err)
if (err) return res.sendStatus(403)
req.user = user
next()
})
}
Example 2: authentication-and-authorization-using-jwt-in-node-js
exports.verifyUserToken = (req, res, next) => {
let token = req.headers.authorization;
if (!token) return res.status(401).send("Access Denied / Unauthorized request");
try {
token = token.split(' ')[1]
if (token === 'null' || !token) return res.status(401).send('Unauthorized request');
let verifiedUser = jwt.verify(token, config.TOKEN_SECRET);
if (!verifiedUser) return res.status(401).send('Unauthorized request')
req.user = verifiedUser;
next();
} catch (error) {
res.status(400).send("Invalid Token");
}
}
Example 3: nodejs authentication token
Setting up our development environment and initializing our express server.
Creating our first basic route and controller.
Fleshing out our routes and controllers to add users and login users.
Creating a route and controller that will handle getting all users.
Example 4: token authentication in nodejs
If the request contains the access token, then the server will verify whether it was issued by the server itself using the stored secret. In case the token is expired or recognized as a one not signed by the server, the jsonwebtoken’s verify method will throw an error. We can handle the error to return a 401 error back to the client.