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
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:
In order to verify a token you need to pass 2 parameters:
'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.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:
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 usingconst decode=req.decode;
Check some examples here: