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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With