DEV Community

Cover image for OAuth 2.0 Authentication with Passport.js: Secure Google, Facebook & GitHub Login
Abhay Prajapati
Abhay Prajapati

Posted on

3 1

OAuth 2.0 Authentication with Passport.js: Secure Google, Facebook & GitHub Login

Authentication is a crucial part of modern web applications. Instead of asking users to create new accounts, integrating social login with Google, Facebook, and GitHub can enhance the user experience. In this guide, we’ll use Passport.js, a popular authentication middleware for Node.js, to implement OAuth 2.0 authentication.

🚀 Benefits of Using OAuth 2.0 with Passport.js

  • Security: Users don’t need to create new credentials, reducing risks of password leaks.
  • User Convenience: Quick login via existing social accounts.
  • Reduced Development Time: Prebuilt strategies simplify implementation.
  • Scalability: Easily integrates into various applications with minimal effort.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js and npm
  • MongoDB (or any other database for storing user sessions, if needed)
  • A basic understanding of Express.js and Passport.js

Step 1: 🛠 Setting Up a Node.js Project

Non-blocking architecture ensures smooth authentication processes.

mkdir passport-auth
cd passport-auth
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: 📦 Installing Required Dependencies

Using environment variables (dotenv) ensures credentials are kept secure.

npm install express passport passport-google-oauth20 passport-facebook passport-github express-session dotenv mongoose cors
Enter fullscreen mode Exit fullscreen mode

Explanation of Dependencies

  • passport: Authentication middleware
  • passport-google-oauth20: Google OAuth 2.0 strategy
  • passport-facebook: Facebook OAuth 2.0 strategy
  • passport-github: GitHub OAuth 2.0 strategy
  • express-session: To manage sessions
  • dotenv: To manage environment variables
  • mongoose: MongoDB ODM (optional for storing user info)
  • cors: To enable Cross-Origin Resource Sharing

Step 3: 🌐 Creating the Server

CORS ensures the frontend can communicate with the backend securely.
Create an index.js file and set up an Express server.

require("dotenv").config();
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const cors = require("cors");

const app = express();
app.use(express.json());
app.use(cors({ origin: "http://localhost:5173", credentials: true }));
app.use(session({ secret: "secret", resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

app.get("/", (req, res) => {
    res.send("Welcome to OAuth 2.0 Authentication with Passport.js");
});

app.listen(3000, () => console.log("Server running on port 3000"));
Enter fullscreen mode Exit fullscreen mode

Step 4: 🔐 Setting Up OAuth Providers

OAuth 2.0 eliminates the need for password storage, minimizing security risks.

4.1 Configuring Google OAuth 2.0

Register your app on Google Developer Console, get your Client ID and Client Secret, and set up the callback URL (http://localhost:3000/auth/google/callback).

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"
}, (accessToken, refreshToken, profile, done) => {
    done(null, profile);
}));

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

app.get("/auth/google/callback", passport.authenticate("google", {
    successRedirect: "http://localhost:5173/profile",
    failureRedirect: "http://localhost:5173/login"
}));
Enter fullscreen mode Exit fullscreen mode

4.2 Configuring Facebook OAuth 2.0

Go to Facebook Developers, create an app, and get your credentials.

const FacebookStrategy = require("passport-facebook").Strategy;

passport.use(new FacebookStrategy({
    clientID: process.env.FACEBOOK_CLIENT_ID,
    clientSecret: process.env.FACEBOOK_CLIENT_SECRET,
    callbackURL: "/auth/facebook/callback",
    profileFields: ["id", "displayName", "emails"]
}, (accessToken, refreshToken, profile, done) => {
    done(null, profile);
}));

app.get("/auth/facebook", passport.authenticate("facebook"));

app.get("/auth/facebook/callback", passport.authenticate("facebook", {
    successRedirect: "http://localhost:5173/profile",
    failureRedirect: "http://localhost:5173/login"
}));
Enter fullscreen mode Exit fullscreen mode

4.3 Configuring GitHub OAuth 2.0

Register your app at GitHub Developer Settings and obtain your credentials.

const GitHubStrategy = require("passport-github").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) => {
    done(null, profile);
}));

app.get("/auth/github", passport.authenticate("github"));

app.get("/auth/github/callback", passport.authenticate("github", {
    successRedirect: "http://localhost:5173/profile",
    failureRedirect: "http://localhost:5173/login"
}));
Enter fullscreen mode Exit fullscreen mode

Step 5: 🖥 Implementing OAuth on the Frontend

Users don’t need to create a new account manually.
For the frontend, use React.js and create a simple login UI:

import React from "react";

const Login = () => {
    return (
        <div>
            <h1>Login with OAuth</h1>
            <a href="http://localhost:3000/auth/google">Login with Google</a>
            <a href="http://localhost:3000/auth/facebook">Login with Facebook</a>
            <a href="http://localhost:3000/auth/github">Login with GitHub</a>
        </div>
    );
};

export default Login;
Enter fullscreen mode Exit fullscreen mode

🎯 Conclusion

In this guide, we successfully implemented OAuth 2.0 authentication using Passport.js with Google, Facebook, and GitHub, along with a simple frontend login page in React. This setup allows users to log in seamlessly without needing separate credentials for your application. You can expand this by integrating a database and session management for production use.

If you found this guide helpful, share your thoughts in the comments! 🚀

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more