简体   繁体   中英

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.

I'm getting a 401 unauthorized response error:

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/

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).

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 . If you look at the ruby example they use Time.now.to_i which returns an epoch time in seconds. Javascript's Date.now() returns an epoch time in milliseconds which is too large, you should try dividing Date.now() by 1000, for example:

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:

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

Using divide by 1000 and Math.floor for proper integer conversion - I was able to get GithubAPI to work with the jwt.sign .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM