skip to Main Content

I am working on API in nodejs/expressjs, Right now I am working with "JWT TOKEN" for this I created function for "generate jwt token", now i want to verify that token but I am getting the following errors

JsonWebTokenError: jwt malformed

Here is my current code

const secretKey = 'mySecretKey';
const logins = async (req, res) => {
const user = { id: 123, phoneNumber:'123XXXXXXXX' };
  // Create a JWT token with the user payload and the secret key
  const token = jwt.sign(user, secretKey);
  // Return the token to the client
  res.json({ token });
}


function verifyToken(req, res, next) {
 const token = req.body.token;
  if (token) {
    const decode = jwt.verify(token, "secret");
    res.json({
      login: true,
      data: decode,
    });
  } else {
    // Return response with error
    res.json({
      login: false,
      data: "error",
    });
  }
}

I have a few questions regarding this

1) How can we create a common function for all other APIs ( if the token does not match then display an error)
2) How can we verify the token?

2

Answers


  1. jwt malformed is an error that will occur when the token is null or when it has invalid signature. In your example you have invalid signture and you should change this line of code:

    const decode = jwt.verify(token,"mySecretKey");
    

    In order to verify a token you need to pass 2 parameters:

    1. The token (like you done correctly)
    2. The secrety key. In your code you created the token using the key 'mySecretKey' and then you tried to verify it using the key "secret" which is not right. You should use the same key for sign and the same for verify.

    Check this question for more info: Json Web Token verify() return jwt malformed

    Regarding your question How can we create common function for all other api the easiest way is to wrap the code inside try/catch blocks and if the verify fails send the error.

    function verifyToken(req, res, next) {
      try {
        const token = req.body.token;
        if (token) {
          const decode = jwt.verify(token, "mySecretKey");
          return res.json({
            login: true,
            data: decode,
          });
        } else {
          // Return response with error
          return res.json({
            login: false,
            data: "error",
          });
        }
      } catch (error) {
        return res.status(500).send(error);
      }
    }
    
    Login or Signup to reply.
  2. So what you want to do in order to use the verification everywhere without rewriting it is by using it as a middleware like this:

    function verifyToken(req, res, next) {
      try {
        const token = req.body.token;
        if (token) {
          const decode = jwt.verify(token, "mySecretKey");
          // The next function will have access to this
          req.decode=decode;
          // If the decode is successful you will continue to the next function
          next();
        } else {
          // Return response with error
          return res.json({
            login: false,
            data: "error",
          });
        }
      } catch (error) {
        return res.status(500).send(error);
      }
    }
    

    For example you want to call the addrecord. In your server file you will use app.use(verifyToken,addRecord). This means that before addRecord function is called the verifyToken function will be called first and only if it verify the token it will continue to the addRecord function. Also you will now have access to the decode variable inside the addRecord function by using

    const decode=req.decode;
    Check some examples here:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search