Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GitHub Octokit/rest.js OAuth for Single Page Applications

I am using the GitHub API client 'octokit/rest.js' in an Angular single page application (SPA). Given that it is generally more secure and that I use 2 factor authentication for my GitHub account (password alone is not enough) I wanted to make use of the OAuth workflow. I've been following the instructions here for obtaining an access token and then use this to build the octokit client:

login(token: string) {
  this.client = new Octokit({
    auth: `token ${token}`
  });
}

In order to fetch the token I've had to make a simple backend, whose purpose is simply to get the token and pass it to the front-end, as I haven't worked out how to do this securely from within the SPA (it requires a client_secret which I can't keep secure on the front end?). It seems to to work but I'm still left with important questions:

  • Is this secure? Or should the access token be kept only server side?
  • Is there a better way of handling octokit/GitHub API auth from the front end only?
like image 601
peter554 Avatar asked Feb 24 '26 13:02

peter554


1 Answers

ocotkit/rest.js maintainer here ๐Ÿ‘‹

The client_secret cannot be shared with the client. The OAuth flow requires a backend which keeps the client_secret secure.

An alternative is to create a token using your username & password, in that case you donโ€™t need a server component. But usually users might be reluctant to share their login credentials with an external website. But for personal/internal projects it might be the simplest way to do it.

let octokit = new Octokit({
  auth: {
    username: USERNAME,
    password: PASSWORD,
    on2fa () {
      return prompt('Enter code')
    }
  }
})

octokit.oauthAuthorizations.createAuthorization({
  scopes: [], // add scopes
  note: 'token description'
})

  .then(({ data: { token } }) => {
    octokit = new Octokit({ auth: 'token ${token}' })
    // octokit is now authenticated with token
  })

Note that the token note must be unique. If you created a token with the same note before, you will need to use a different note or delete the existing token first.

We are currently considering to add more auth.* options, so that a token gets created for you internally before any request is sent. We are discussing this change at https://github.com/octokit/rest.js/pull/1293 if you are interested

like image 165
Gregor Avatar answered Feb 27 '26 02:02

Gregor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!