Node.js › Authentication & Authorization (JWT, OAuth, Passport)
How would you implement 'Sign in with GitHub' using Passport's OAuth strategy in an Express application?
IntermediateAnswer
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.