尝试生成访问令牌时,GitHub API返回401

时间:2020-05-13 09:05:52

标签: node.js github-api github-app

我正在尝试通过GitHub API为我的GitHub应用生成访问令牌。

我收到401未经授权的响应错误:

expiration time' claim ('exp') is too far in the future

我的代码:

const now = Date.now()
const expiration = now + 60 * 10 // JWT expiration time (10 minute maximum)

const payload = {
  iat: now
  exp: expiration,
  iss: appId
}

const jwt = jwtGenerator(payload, privatePem, { algorithm: "RS256" })

Github文档-https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/

2 个答案:

答案 0 :(得分:3)

我发现了问题所在。

不同机器上的时间不同步。 为了解决这一问题,我将过去的空闲时间设置为30秒(我尝试了不同的时间跨度,但事实证明30秒效果最好)。

const now = Math.floor(Date.now() / 1000) - 30
const expiration = now + 60 * 10 // JWT expiration time (10 minute maximum)

const payload = {
  iat: now,
  exp: expiration,
  iss: appId
}

const jwt = jwtGenerator(payload, privatePem, { algorithm: "RS256" })

答案 1 :(得分:0)

Github可能期望exp下的纪元时间以秒为单位。 如果您查看ruby示例,它们将使用Time.now.to_i来返回以秒为单位的纪元时间。 Javascript的Date.now()返回的纪元时间(以毫秒为单位)太大,您应尝试将Date.now()除以1000,例如:

const now = (Date.now() / 1000)
const expiration = now  + (60 * 10) // JWT expiration time (10 minute maximum)

const payload = {
  iat: now
  exp: expiration,
  iss: appId
}

const jwt = jwtGenerator(payload, privatePem, { algorithm: "RS256" })

jsonwebtoken的文档特别提到:

IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch"

使用1000Math.floor除以进行正确的整数转换-我能够使GithubAPI与jwt.sign一起使用。