How would you implement 'Sign in with GitHub' using Passport's OAuth strategy in an Express application?
Short answer
Using passport-github2 (or a similar strategy package), you register the strategy with your app's client ID and secret, define a callback that receives the authenticated GitHub profile and finds-or-creates a corresponding local user record, and wire up two routes: one that…
Advertisement
AModel answer
Using passport-github2 (or a similar strategy package), you register the strategy with your app's client ID and secret, define a callback that receives the authenticated GitHub profile and finds-or-creates a corresponding local user record, and wire up two routes: one that redirects the user to GitHub to begin the OAuth flow, and one matching GitHub's configured callback URL that completes the exchange.
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: '/auth/github/callback',
}, async (accessToken, refreshToken, profile, done) => {
const user = await User.findOrCreate({ githubId: profile.id, name: profile.displayName });
done(null, user);
}));
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (req, res) => res.redirect('/dashboard'));Real-world example
A developer-tools SaaS product offers 'Sign in with GitHub' as its only authentication method, using Passport's GitHub strategy to handle the entire OAuth handshake and automatically create a local user record on a developer's very first login.
Likely follow-ups
- How does the findOrCreate pattern handle a user who signs in with GitHub after already having an account created via email/password?
- What GitHub OAuth scopes would need to be requested to also read the user's repositories, beyond basic profile info?
Related topics