簡體   English   中英

GitHub API 在嘗試生成訪問令牌時返回 401

[英]GitHub API returns 401 while trying to generate access token

我正在嘗試通過 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/

我弄清楚了問題所在。

不同機器上的時間不同步。 為了解決這個問題,我將 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 可能期望在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] 定義“自紀元以來的秒數”

使用除以1000Math.floor進行正確的 integer 轉換 - 我能夠讓 GithubAPI 與jwt.sign一起使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM