Jsonwebtoken : invalid token

Issue

I setup JWT in my express app and I get this error : invalid token. But when I copy this token to jwt.io, exp date is correct and data ok.

Here is my controller :

module.exports.signIn = async (req, res) => {
  const { email, password } = req.body;
  const user = await UserModel.findOne({ email });

  if (!user) {
    return res.status(400).json({
      message: "User not found."
    });
  }

  const isValidPassword = await bcrypt.compare(password, user.password);

  if (!isValidPassword) {
    return res.status(400).json({
      message: "Invalid password."
    });
  }

  const token = jwt.sign({ id: user._id }, process.env.SECRET_KEY, {
    expiresIn: "10h"
  });

  res.status(200).json({
    message: "User logged in.",
    token
  });
};

And my middleware :

const jwt = require("jsonwebtoken");

module.exports.verifyToken = (req, res, next) => {
  const token = req.headers.authorization;
  console.log(token);

  if (!token) {
    return res.status(403).json({
      message: "No token provided."
    });
  }

  jwt.verify(token, process.env.SECRET_KEY, (err, decoded) => {
    if (err) {
      return res.status(401).json({
        message: "Unauthorized."
      });
    }

    req.userId = decoded.id;
    next();
  });
};

What I do is :

  • sign in
  • copy token to Headers authorizations
  • make my get request to another route that has the verifyToken

And then I get the error.

When I console.log(token) I get Bearer ...[the token]

Any idea why ?

Solution

You need four arguments in the verify function

jwt.verify(token, process.env.PUBLIC_KEY, {}, (err, decoded) => {

                if (err !== null && err instanceof TokenExpiredError) {
                    cb('TOKEN_EXP');
                    return Json.builder(Response.HTTP_UNAUTHORIZED_TOKEN_EXP);
                }

                if (err instanceof JsonWebTokenError) {
                    cb('IN_VALID_TOKEN');
                    return Json.builder(Response.HTTP_UNAUTHORIZED_INVALID_TOKEN);
                }

                cb(decoded);
            });

Answered By – Ali Azmoodeh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published