OAuth and Third-Party Authentication (Google, GitHub, etc.)
OAuth and Third-Party Authentication (Google, GitHub, etc.)
Last updated: 3/7/2025
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
- Go to Google Cloud Console β https://console.cloud.google.com/
- Create a new project.
- Navigate to APIs & Services > Credentials.
- Click "Create Credentials" > OAuth Client ID.
- Choose Web Application.
- Set the Authorized Redirect URI:
http://localhost:3033/auth/google/callback
- 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:
Provider | Install Command |
---|---|
GitHub | npm install passport-github2 |
npm 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.