Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to sign a jwt returns undefined

I'm learning node and I'm migrating my current API from python. I'm trying to create a jwt token to authenticate in a third party API, however my function returns undefined. The jwt method I'm using to sign the token is async, so I guess my function doesn't wait until jwt returns the token.

This is my function to sign and create the jwt token:

function token() {
  const payload = {
    iat: Math.floor(new Date() / 1000),
    exp: Math.floor(new Date() / 1000) + 30,
    sub: "api_key_jwt",
    iss: "external",
    jti: crypto.randomBytes(6).toString("hex")
  };
  return jwt.sign(payload, privatekey, { algorithm: "RS256" }, function(
    err,
    token2
  ) {
    return token2;
  });
}

So, when I call it:

exports.genToken = function() {
  const header = {
    "x-api-key": api
  };
  const data = {
    kid: api,
    jwt_token: token()
  };

  async function authorization(req, res) {
    try {
      const auth = await rp({
        url: authurl,
        method: "POST",
        headers: header,
        body: data
      });
      res.send(auth.body);
    } catch (error) {
      res.send(404).send();
    }
  }

  return {
    "x-api-key": api,
    Authorization: "Bearer " + authorization()
  };
};

jwt_token returns undefined. What am I doing wrong, and how can I fix it?

Thanks in advance guys!

Edit: console.log(token2) returns the signed token. So the problem is returning the token from the token() function

like image 721
Otavio Bonder Avatar asked Oct 16 '25 04:10

Otavio Bonder


1 Answers

You're trying to return from a callback which doesn't work. Change your token function to return Promise then you can use the async/await like:

function token() {
  ...

  return new Promise((resolve, reject) => {
    jwt.sign(payload, privatekey, { algorithm: "RS256" }, function(err, token2) {
      if (err) reject(err);
      else resolve(token2)
    });
  })
}

// note async
exports.genToken = async function() {
  ...
  const data = {
    kid: api,
    jwt_token: await token()
  };
  ...
}

like image 95
1565986223 Avatar answered Oct 17 '25 16:10

1565986223