[英]GitHub API returns 401 while trying to generate access token
I'm trying to generate an access token for my GitHub App via GitHub API.我正在尝试通过 GitHub API 为我的 GitHub 应用程序生成访问令牌。
I'm getting a 401 unauthorized response error:我收到 401 未经授权的响应错误:
expiration time' claim ('exp') is too far in the future
My code:我的代码:
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 documentation - https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/ Github 文档 - https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/
I figured out what was the problem.我弄清楚了问题所在。
The times on different machine were not in sync.不同机器上的时间不同步。 To solve that I set the iat time 30 secs in the past (I tried different time span but it turned out that 30 sec works the best).
为了解决这个问题,我将 iat 时间设置为过去 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" })
Github might be expecting an epoch time in seconds under exp
. Github 可能期望在
exp
下以秒为单位的纪元时间。 If you look at the ruby example they use Time.now.to_i
which returns an epoch time in seconds.如果您查看 ruby 示例,他们使用
Time.now.to_i
以秒为单位返回纪元时间。 Javascript's Date.now()
returns an epoch time in milliseconds which is too large, you should try dividing Date.now()
by 1000, for example: 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" })
The documentation for jsonwebtoken
specifically mentions: jsonwebtoken
的文档特别提到:
IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch" IEEE Std 1003.1, 2013 Edition [POSIX.1] 定义“自纪元以来的秒数”
Using divide by 1000
and Math.floor
for proper integer conversion - I was able to get GithubAPI to work with the jwt.sign
.使用除以
1000
和Math.floor
进行正确的 integer 转换 - 我能够让 GithubAPI 与jwt.sign
一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.