OAuth 2.0 and Social LoginLesson 4.5
OAuth callback routes and session handling with Passport
passport.authenticate, failureRedirect, successRedirect, custom callback, req.login, req.logout, req.isAuthenticated, route protection with passport
Wiring Routes
app.use(passport.initialize());
app.use(passport.session());
// Initiates OAuth redirect
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
// Handles the callback
app.get('/auth/google/callback',
passport.authenticate('google', {
failureRedirect: '/login?error=oauth_failed',
successRedirect: '/dashboard'
})
);
// Logout
app.post('/auth/logout', (req, res) => {
req.logout((err) => {
if (err) return res.status(500).end();
res.redirect('/login');
});
});
// Route protection
function ensureAuth(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
app.get('/dashboard', ensureAuth, (req, res) => {
res.json({ user: req.user });
});
Custom Callback Pattern
If you need to inspect the OAuth result before redirecting (e.g., to return a JWT instead of using session), use a custom callback instead of successRedirect. Call req.login(user, cb) manually if you want Passport to serialize the user into the session.
