Skip to main content

Github

Register your app in Github's Dashboard

To use the Github Provider you will need a client id and a client secret. You will get them while following the process to setup Github OAuth 2.0 for your application. Follow the instructions in the following link:

info

When asked for an origin URL, insert the origin of the url in which your app is hosted.

Examples:

  • http://localhost:3000
  • https://www.example.com

When asked for a redirect URL (or callback), insert[http or https]://[origin]/[your route for Github authentication]

Examples:

  • http://localhost:8000/auth/github
  • https://www.example.com/api/login/github
  • https://www.example.com/godel/russell/myGithubLogin

Github's official guide (Follow the guide until you get a client id and client secret and setup a callback. Don't worry about the rest, Gatekeeper will take care of that): https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app

Github Provider

Options

Option nameDescriptionDefault valueRequired?
clientIdYour Github OAuth client idYes
clientSecretYour Github OAuth client secretYes
callbackURLThe URL that will serve as callback for Github OAuthYes
scopeThe OAuth scopes that will be granted to the access token['user']No
danger

To the callbackURL option you must provide the URL you provided when asked for a redirect (or callback) URL when registering your Github OAuth app.

Handler

The Github Provider passes three parameters to the handler:

  • refresh_token: The OAuth refres token. It is usually only given the first time a user signs-in to your application
  • access_token: The OAuth access token.
  • profile: The information of the Github user.

Errors

The predefined errors of this provider are:

  • UserNotFound

Examples

Example #1

Create a Github Provider

import gatekeeper from 'gatekeeper-authentication'
import { GithubProvider } from 'gatekeeper-authentication/providers/github'

const GithubAuth = new GithubProvider({
clientId: '<YOUR GITHUB CLIENT ID>',
clientSecret: '<YOUR GITHUB CLIENT SECRET>',
callbackURL: 'https://www.yourdomainorlocalhost.com/auth/github'
}, function handler(refresh_token, access_token, profile) => {
const user = User.findOne({ githubId: profile.sub })

if (user == null) {
// For example, if the user does not exist, create it
User.create({
username: profile.name,
profilePicture: profile.picture
});
}

return user;
});

Login with a Github Provider

warning

Important: When using the Github provider on login routes, make sure you use gatekeeper.authenticateWithProvider(yourGithubProvider) in a GET route, as the user will be redirected to Github's sign in page

router.get(
'/auth/github',
gatekeeper.authenticateWithProvider(GithubAuth), (req, res) => {
return res.redirect('/profile');
}
);