0

my verify token function returns undefined instead of true,the issuetoken function issues a token ,the verify token function verifies the token issued.

var jwt = require('jsonwebtoken'); //import the jwt mmodule
var secret = process.env.JWT_SECRET || "david"; // secret question

//issue token function
issuetoken = function (username) {
  var token = jwt.sign({
    username,
    exp: Math.floor(Date.now() / 1000) + (60 * 60),
  }, secret);

  return token;
}

//this function verifies the token, it return true if verification is succesfull and return false if not successfull            
verifytoken = function (token, secret) {
  jwt.verify(token, secret, function (err, vt) {      
    if (err) {
      console.log(err);
      return false;
    }      
    else {
      return true;       
    }
  });
}

var token = issuetoken("david");// issue the token with username david
var a = verifytoken(token, secret); //verification of token
console.log(a);  //it returns undefined instead of true
Yoni Levy
  • 1,562
  • 2
  • 16
  • 35
linux
  • 141
  • 2
  • 12

1 Answers1

1

jwt.verify is asynchronous but you're are treating it in a synchronous fashion.

If you want to know when the token was verified you need to pass some sort of callback or maybe return a Promise

Callback

verifytoken = function (token, secret, callback) {
  jwt.verify(token, secret, function (err, vt) {      
    if (err) {
      // decide what to do with the error...
      callback(false);
    }      
    else {
      callback(true);       
    }
  });
}

var token = issuetoken("david"); //"issues the token with username david"
verifytoken(token, secret, console.log);// verifies the token and prints to the console when done.

Promise

verifytoken = function (token, secret) {
  return new Promise(function(resolve, reject) {
    jwt.verify(token, secret, function (err, vt) {
      if (err) {
        // decide what to do with the error...
        reject(false);
      }      
      else {
        resolve(true);       
      }
    })
  })
}

var token = issuetoken("david"); //"issues the token with username david"
verifytoken(token, secret) // verifies the token
  .then(console.log)       // prints to the console when done.
  .error(console.error)    // prints errors

In case jwt.verify already returns a promise you can just return its result

EDIT

I took a look into jwt docs and you can do synchronously. You must omit the callback.

verifytoken = function (token, secret) {
  try {
    jwt.verify(token, secret)
    return true
  } catch(err) {
    return false
  }    
}
Yoni Levy
  • 1,562
  • 2
  • 16
  • 35