Girish Patil
Evilspace

Evilspace

Update Github access tokens to new format via Github API

Girish Patil's photo
Girish Patil
·Jan 20, 2022·

2 min read

Update Github access tokens to new format via Github API

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Interacting with Github APIs has always been a little tricky task for me. Recently we had to update the Github access tokens as they have changed the formats of the access tokens.

Read more about it here - github.blog/2021-04-05-behind-githubs-new-a..

So, writing this post so that it can help you if you are in the same boat.

Things to note

There are two ways to reset the access tokens. One is letting the users go through the auth/installation flows again or you can do it silently for your users via Github APIs. This post is all about that API way.

Since the API hit instantaneously resets the token and returns it in the API response. You will have to make sure that is stored somewhere or you update the respective record in the database on your end. Because if you lose it the old tokens are of no use and you will have to let users go through the auth flows/app installation flows, etc. again.

I will not be using Octokit, feels like it is either complicated or I spend lots of time figuring things out every time. So, a simple fetch call should do that job.

Making the API request

(async function () {
  await fetch(`https://api.github.com/applications/${GITHUB_APP_CLIENT_ID}/token`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Basic ' + Buffer.from(GITHUB_APP_CLIENT_ID + ":" + GITHUB_APP_CLIENT_SECRET).toString('base64'),
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      access_token: YOUR_USER_ACCESS_TOKEN
    })
  });
})();

Just to be on the safer side, you can use a lightweight database like NEDB (github.com/louischatriot/nedb) and store every API response along with user details in the DB.

Then, wrote another script that reads that NEDB database file and updates the actual records in our main database accordingly. Since NEDB is light and stores everything in a single file it's easier to debug if something goes wrong, reset/re-run things in such cases.

You can also update the respective user's token as soon as you get the API response. With this, you will not be in control over the whole process. If anything breaks or something unexpected happens and if you lose the new access token, then it's all waste of time.

P.S You will hit rate limits after about 60 requests when the requests are unauthenticated. Read more about other gotchas here docs.github.com/en/rest/reference/apps#rese..

 
Share this