最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trying to sign a jwt returns undefined - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question edited Apr 18, 2019 at 14:43 Otavio Bonder asked Apr 18, 2019 at 14:36 Otavio BonderOtavio Bonder 1,9995 gold badges22 silver badges38 bronze badges 2
  • Can you console.log the err variable in the callback function and post it's results? Does it contain an error? – George Koniaris Commented Apr 18, 2019 at 14:40
  • Hi George, I edited the question. Actually the token is being signed by the jwt.sign, however it doesn't return to the token() function – Otavio Bonder Commented Apr 18, 2019 at 14:44
Add a ment  | 

2 Answers 2

Reset to default 5

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()
  };
  ...
}

Here is the catch if you supply jwt.sign with the callback function it will work in async mode and going to return undefined so just omit the callback and it will work your function will look like

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" });
}
发布评论

评论列表(0)

  1. 暂无评论