Script Valley
REST API Development: Complete Course from Beginner to Production
Authentication and Security in REST APIsLesson 4.5

OAuth 2.0 and Social Login: Concepts and Integration

OAuth 2.0, authorization code flow, access token, refresh token, Google OAuth, GitHub OAuth, Passport.js, social login, scopes

OAuth 2.0 and Social Login: Concepts and Integration

OAuth 2.0 is an authorization framework that enables applications to obtain limited access to user accounts on third-party services without exposing passwords. It powers the Sign in with Google, Sign in with GitHub, and Sign in with Apple buttons used in virtually every modern application.

OAuth 2.0 Authorization Code Flow

The authorization code flow has these steps: the user clicks Sign in with Google on your app, your app redirects to Google's authorization server, the user logs in on Google and grants permissions, Google redirects back to your callback URL with an authorization code, your server exchanges the code for access and refresh tokens server-to-server, your server uses the access token to fetch the user's profile, then creates or updates the user in your database and issues your own JWT.

Passport.js Integration

npm install passport passport-google-oauth20
passport.use(new GoogleStrategy({
  clientID: process.env.GOOGLE_CLIENT_ID,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  callbackURL: '/api/auth/google/callback'
}, async (accessToken, refreshToken, profile, done) => {
  let user = await User.findOne({ googleId: profile.id });
  if (!user) {
    user = await User.create({
      googleId: profile.id,
      name: profile.displayName,
      email: profile.emails[0].value
    });
  }
  return done(null, user);
}));

OAuth Scopes

Scopes define exactly what permissions your application is requesting. Always request the minimum scopes necessary. For a login flow, request openid email profile — do not request calendar, contacts, or file access unless your application explicitly needs them.