Topics Authentication & Security OAuth & Social Login
advanced 18 min read

OAuth & Social Login

Implement OAuth 2.0 flows and social login with Google, GitHub, and other providers.

OAuth 2.0 Flow

// Using Passport.js for social auth\nconst passport = require('passport');\nconst GoogleStrategy = require('passport-google-oauth20').Strategy;\nconst GitHubStrategy = require('passport-github2').Strategy;\n\n// Google\npassport.use(new GoogleStrategy({\n  clientID: process.env.GOOGLE_CLIENT_ID,\n  clientSecret: process.env.GOOGLE_CLIENT_SECRET,\n  callbackURL: '/auth/google/callback',\n}, async (accessToken, refreshToken, profile, done) => {\n  let user = await User.findOne({ googleId: profile.id });\n  \n  if (!user) {\n    user = await User.create({\n      googleId: profile.id,\n      name: profile.displayName,\n      email: profile.emails[0].value,\n      avatar: profile.photos[0].value,\n    });\n  }\n  \n  done(null, user);\n}));\n\n// Routes\napp.get('/auth/google', passport.authenticate('google', {\n  scope: ['profile', 'email'],\n}));\n\napp.get('/auth/google/callback', passport.authenticate('google', {\n  successRedirect: '/dashboard',\n  failureRedirect: '/login',\n}));

Session vs Token

  • Session-based: Server stores session, sends cookie
  • JWT-based: Token stored client-side, no server state
  • OAuth 2.0: Delegated authorization via third-party

Examples

const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;

// Simplified OAuth handler
passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID || 'your-client-id',
  clientSecret: process.env.GOOGLE_CLIENT_SECRET || 'your-secret',
  callbackURL: '/api/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
  // Find or create user
  User.findOne({ email: profile.emails[0].value })
    .then(user => {
      if (user) return done(null, user);
      
      return User.create({
        name: profile.displayName,
        email: profile.emails[0].value,
        avatar: profile.photos?.[0]?.value,
        provider: 'google',
        providerId: profile.id,
      }).then(newUser => done(null, newUser));
    })
    .catch(err => done(err, null));
}));

// Express routes
const authRouter = express.Router();

authRouter.get('/google',
  passport.authenticate('google', {
    scope: ['profile', 'email'],
    session: false,
  })
);

authRouter.get('/google/callback',
  passport.authenticate('google', { session: false }),
  (req, res) => {
    const token = jwt.sign({ userId: req.user.id }, process.env.JWT_SECRET);
    res.redirect(`/dashboard?token=${token}`);
  }
);

console.log('OAuth routes configured');

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.