Shahar Yakov
Shahar Yakov

Reputation: 426

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/

Upvotes: 3

Views: 1800

Answers (2)

Shahar Yakov
Shahar Yakov

Reputation: 426

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" })

Upvotes: 3

Rewire
Rewire

Reputation: 361

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.

Upvotes: 0

Related Questions