OAuth and Third-Party Authentication (Google, GitHub, etc.)

OAuth and Third-Party Authentication (Google, GitHub, etc.)

Last updated: 3/7/2025

1 hour
Medium

OAuth and Third-Party Authentication (Google, GitHub, etc.)

🌍 Introduction

OAuth allows users to log in using third-party services like Google, GitHub, Facebook, or Twitter instead of creating new accounts.

βœ… Why Use OAuth?

βœ” Convenience – Users don’t need to remember another password.
βœ” Security – No need to store passwords, reducing breach risks.
βœ” Faster Signups – Users can sign up in one click.

In this lesson, we’ll:

  • Understand how OAuth works.
  • Implement Google Login in an Express.js API.
  • Securely handle authentication tokens.

πŸ“Œ 1. How OAuth Authentication Works

βœ… OAuth Flow (Google Example)

1️⃣ User clicks "Login with Google" β†’ Redirects to Google.
2️⃣ Google asks for permission β†’ User approves access.
3️⃣ Google sends an authorization code back to our API.
4️⃣ Our API exchanges the code for a Google access token.
5️⃣ We use the access token to get the user’s profile information.

πŸ”Ή No passwords are handled by our API!
πŸ”Ή The user’s identity is verified by Google, GitHub, etc.


πŸ“Œ 2. Setting Up Google OAuth in an Express.js API

βœ… Step 1: Create a Google OAuth Client

  1. Go to Google Cloud Console β†’ https://console.cloud.google.com/
  2. Create a new project.
  3. Navigate to APIs & Services > Credentials.
  4. Click "Create Credentials" > OAuth Client ID.
  5. Choose Web Application.
  6. Set the Authorized Redirect URI:
    http://localhost:3033/auth/google/callback
  7. Copy Client ID and Client Secret.

βœ… Step 2: Install Dependencies

Run:

npm install express passport passport-google-oauth20 dotenv

βœ” passport β†’ Authentication middleware
βœ” passport-google-oauth20 β†’ Google OAuth strategy
βœ” dotenv β†’ Store sensitive keys securely


βœ… Step 3: Configure Google OAuth Strategy

Create auth/google.js:

const passport = require("passport"); const GoogleStrategy = require("passport-google-oauth20").Strategy; require("dotenv").config(); passport.use( new GoogleStrategy( { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: "/auth/google/callback" }, (accessToken, refreshToken, profile, done) => { return done(null, profile); } ) ); // Serialize user data into session passport.serializeUser((user, done) => { done(null, user); }); // Deserialize user data from session passport.deserializeUser((user, done) => { done(null, user); });

βœ… Google handles authentication and returns user data.


βœ… Step 4: Implement OAuth Routes

Modify routes/auth.js:

const express = require("express"); const passport = require("passport"); const router = express.Router(); // Route to start Google login router.get("/google", passport.authenticate("google", { scope: ["profile", "email"] })); // Callback route after Google authentication router.get("/google/callback", passport.authenticate("google", { failureRedirect: "/" }), (req, res) => { res.json({ message: "Logged in successfully!", user: req.user }); }); // Logout Route router.get("/logout", (req, res) => { req.logout(() => { res.json({ message: "Logged out successfully" }); }); }); module.exports = router;

βœ… Users are redirected to Google for authentication.
βœ… Upon success, user data is retrieved and returned as JSON.


βœ… Step 5: Register Routes in server.js

Modify server.js:

const express = require("express"); const session = require("express-session"); const passport = require("passport"); require("./auth/google"); // Load Google OAuth config const app = express(); app.use(session({ secret: "supersecret", resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); const authRoutes = require("./routes/auth"); app.use("/auth", authRoutes); app.listen(3033, () => console.log("Server running on port 3033"));

βœ… Session-based authentication allows users to stay logged in.
βœ… Passport manages authentication and stores user info in a session.


πŸ“Œ 3. Testing Google OAuth Login

βœ… 1️⃣ Start the Server

Run:

node server.js

βœ… 2️⃣ Log In with Google

Open http://localhost:3033/auth/google
βœ” Redirects to Google login
βœ” On success, redirects to /auth/google/callback

Response:

{ "message": "Logged in successfully!", "user": { "id": "113456789012345678901", "displayName": "Alice Johnson", "emails": [{ "value": "alice@example.com" }] } }

βœ… 3️⃣ Logout

GET /auth/logout

βœ” Logs out the user and clears session.


πŸ“Œ 4. Expanding OAuth to GitHub, Facebook, etc.

πŸ”Ή The process is the same for GitHub, Facebook, Twitter, etc.
πŸ”Ή Install the respective Passport strategy:

ProviderInstall Command
GitHubnpm install passport-github2
Facebooknpm install passport-facebook

πŸ”Ή Example: GitHub OAuth

const GitHubStrategy = require("passport-github2").Strategy; passport.use( new GitHubStrategy( { clientID: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackURL: "/auth/github/callback" }, (accessToken, refreshToken, profile, done) => { return done(null, profile); } ) );

🎯 Summary

βœ… OAuth allows users to log in using Google, GitHub, etc.
βœ… Users authenticate via a third-party service instead of passwords.
βœ… Implemented Google Login using Passport.js and Express.js.
βœ… OAuth can be extended to GitHub, Facebook, and other providers.