Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active December 10, 2023 22:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshnuss/5df5465744c9717b2b077252b92a9547 to your computer and use it in GitHub Desktop.
Save joshnuss/5df5465744c9717b2b077252b92a9547 to your computer and use it in GitHub Desktop.
OAuth2 Client
import fetch from 'node-fetch'
// some provider data is copied from github.com/simov/grant
const providers = {
bogus: {
authorize_url: "http://localhost:8282/auth/request/path",
access_url: "http://localhost:8282/access/token/request",
},
google: {
authorize_url: "https://accounts.google.com/o/oauth2/v2/auth",
access_url: "https://oauth2.googleapis.com/token"
},
github: {
authorize_url: "https://github.com/login/oauth/authorize",
access_url: "https://github.com/login/oauth/access_token",
},
}
export default class OAuthClient {
constructor(config) {
this.config = config
this.provider = providers[config.provider]
if (!this.provider) throw new Error(`Unknown OAuth provider ${config.provider}`)
}
authorizeUrl() {
const { client_id, redirect_uri } = this.config
const url = new URL(this.provider.authorize_url)
const params = url.searchParams
params.set('response_type', 'code')
params.set('client_id', client_id)
params.set('redirect_uri', redirect_uri)
return url.toString()
}
async fetchAccessToken(code) {
const { client_id, client_secret } = this.config
const response = await fetch(this.provider.access_url, {
method: 'POST',
body: new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id,
client_secret
})
})
return {
success: response.ok,
payload: await response.json()
}
}
}
import OAuthClient from './OAuthClient.js'
// instantiate the client
const client = new OAuthClient({
provider: 'google',
client_id: '...',
client_secret: '...',
redirect_uri: '...'
})
// Step 1: Generate the authorization url, and redirect the user there
const url = client.authorizationUrl()
redirectTo(url)
// Step 2: When the user returns to the callback url, the url will contain a `code` query param.
// Use that `code` to get the access token
const code = params.get('code')
const response = await client.fetchAccessToken(code)
if (response.success) {
// log the access token
console.log(response.payload)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment