Day 2 of 5
⏱ ~60 minutes
Auth and Security for Web Apps — Day 2

OAuth 2.0 and Social Login: Google, GitHub, and Beyond

OAuth lets users log in with their Google or GitHub account — no password management required. Day 2 implements OAuth 2.0 with Google using Passport.js.

The OAuth 2.0 Flow

OAuth 2.0 is a protocol for delegated authorization. Here is the 5-step flow:

  1. User clicks "Sign in with Google"
  2. Your app redirects to Google's authorization server
  3. User approves access on Google's page
  4. Google redirects back to your callback URL with a code
  5. Your server exchanges the code for an access token and user profile
Terminal
npm install passport passport-google-oauth20 express-session
oauth.js — Google OAuth Setup
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: '/auth/google/callback'
}, async (accessToken, refreshToken, profile, done) => {
  // Find or create user in your database
  let user = await User.findByGoogleId(profile.id);
  
  if (!user) {
    user = await User.create({
      googleId: profile.id,
      email: profile.emails[0].value,
      name: profile.displayName
    });
  }
  
  done(null, user);
}));

passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser((id, done) => User.findById(id).then(user => done(null, user)));

// Routes
app.get('/auth/google', 
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => {
    // Issue JWT after successful OAuth
    const token = jwt.sign({ userId: req.user.id }, process.env.JWT_SECRET, { expiresIn: '15m' });
    res.redirect(`/app?token=${token}`);
  }
);

app.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/');
});
ℹ️
Getting Google credentials: Go to console.cloud.google.com → APIs and Services → Credentials → Create OAuth 2.0 Client ID. Set the callback URL to http://localhost:3000/auth/google/callback for development.
Day 2 Exercise
Implement Google Sign-In
  1. Create a Google OAuth app in Google Cloud Console.
  2. Set up the Passport.js strategy with your credentials in .env.
  3. Add the session middleware and passport.initialize() to your Express app.
  4. Test the full flow: click "Sign in with Google," complete the OAuth, verify the user is created in your database.
  5. Add a /me endpoint that returns the current user's profile from the session.

Day 2 Summary

  • OAuth 2.0: redirect → user approves → get code → exchange for token → get profile.
  • Never store OAuth access tokens long-term — issue your own JWT after successful OAuth.
  • Passport.js handles the OAuth flow; you handle user creation and session management.
Finished this lesson?