I have used jsonwebtoken
for token verification in my Node Application .
Here jwt.sign
works perfectly . But when jwt.verify
gives following error
"auth": false, "message": { "name": "JsonWebTokenError", "message": "invalid token" } }
Here is my Post and Get Router
router.post('/signup',(req,res)=>{
const body = _.pick(req.body,['username','email_id','name','college','password','dob','gender','city','joinedOn','bio']);
User.findOne({'username':body.username},function(err,user){
if(err){
res.status(404).send(err)
}else if(user){
res.status(404).send('User with Username Exists')
}else{
var user = new User(body);
user.save().then((user) => {
var token = jwt.sign({ username: user.username},'secret', {
"algorithm": "HS256",
expiresIn: 86400 // expires in 24 hours
});
res.status(200).send({ auth: true, token: token });
}, (e) => {
res.status(400).send(e)
})
}
})
});
router.get('/me', VerifyToken, function(req, res) {
User.findOne({username:req.username}, function (err, user) {
if (err) return res.status(500).send(err);
if (!user) return res.status(404).send("No user found.");
res.status(200).send(user);
});
});
Below is verifyToken Function
function verifyToken(req, res, next) {
var token = req.headers['x-access-token'];
if (!token)
return res.status(403).send({ auth: false, message: 'No token provided.' });
console.log(token)
jwt.verify(token,'secret', function(err, decoded) {
if (err)
return res.status(500).send({ auth: false, message: err });
//req.username = decoded.username;
console.log(decoded)
next();
});
}
I can't figure out what's wrong in my program .Any suggestions would be appreciated . Thanks
Client machine's time is not synced with NTP server, and caused JWT Token to become invalid due to a token TTL timeout.
There are two ways to fix the error: (RECOMMENDED) Change the application signature algorithm to RS256 instead of HS256. Change the value of your responseType parameter to token id_token (instead of the default), so that you receive an access token in the response.
To verify JWT claimsVerify that the token is not expired. The aud claim in an ID token and the client_id claim in an access token should match the app client ID that was created in the Amazon Cognito user pool. The issuer ( iss ) claim should match your user pool.
jwt.verify(token, secretOrPublicKey, [options, callback]) (Synchronous) If a callback is not supplied, function acts synchronously. Returns the payload decoded if the signature is valid and optional expiration, audience, or issuer are valid. If not, it will throw the error.
If you are passing in a token to your jwt.verify function like so Bearer *************....
, ensure to split the token first before passing it in to jwt by doing
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token)
Hope this helps someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With