1

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 2

0

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I have to create many API ( like "addrecord" , "updaterecord" etc...),Now i dont want to create whole code (verification code) again and again so i just want that how can i authenticate/verifyToken with common function ? Hope you understand my point
In short i want to verify token with every api but without write code again and again so thats why i want to know is this possible to "verifytoken" with common function (verifytoken) or is there any better approach ?
I will post another answer for that in order to provide code.
0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.