DEV Community

Sourov Pal
Sourov Pal

Posted on

Node js JWT Token Verify Middleware

`const jwt =require("jsonwebtoken");
const JwtToken = require("../models/JwtToken");

async function JwtTokenVerify(req, res, next) {
const auhorizationHeader = req.headers.authorization;
let result;

if (!auhorizationHeader || auhorizationHeader == '') {
return res.status(401).json({
error: true,
message: "Access token is missing",
});
}

const token = req.headers.authorization.split(" ")[1];

try {

const jwt_token = await JwtToken.findOne({$and:[{access_token:token}, {is_active:true}, {deleted_at:null}]});

if (!jwt_token) {
  return res.status(403).json({
    error: true,
    message: "Invalid token",
  });
}

result = await jwt.verify(token, jwt_token.token_secret, {expiresIn: jwt_token.expires_in});

req.decoded = result;

next();
Enter fullscreen mode Exit fullscreen mode

} catch (error) {

if (error.name === "JsonWebTokenError") {
  return res.status(403).json({
    error: true,
    message: "Invalid token",
  });
}

if (error.name === "TokenExpiredError") {
  return res.status(403).json({
    error: true,
    message: "Token expired",
  });
}

return res.status(403).json({
  error: true,
  message: "Authentication error",
});
Enter fullscreen mode Exit fullscreen mode

}
}

module.exports = JwtTokenVerify;`

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay