Home >Web Front-end >JS Tutorial >Passport Authentication for Node.js Applications

Passport Authentication for Node.js Applications

William Shakespeare
William ShakespeareOriginal
2025-02-15 09:39:12408browse

Passport Authentication for Node.js Applications

This tutorial demonstrates Facebook and GitHub authentication in a Node.js web application using Passport.js, a popular authentication middleware. Passport simplifies OAuth and OpenID Connect integration.

Key Concepts:

  • Passport.js: A Node.js middleware streamlining authentication with various providers (Facebook, GitHub, Google, etc.).
  • Express.js: A web application framework for Node.js used to build the application's structure and handle routing.
  • OAuth 2.0: The authorization framework used by Facebook and GitHub.
  • Strategies: Passport uses strategies for each provider (e.g., passport-facebook, passport-github).

Application Setup:

  1. Project Initialization: Create a project directory and initialize a Node.js project:

    <code class="language-bash">mkdir AuthApp
    cd AuthApp
    npm init -y</code>
  2. HTML Setup: Create auth.html in the project root:

    <code class="language-html"><!DOCTYPE html>
    
    
      <title>Node.js OAuth</title>
    
    
      <a href="https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76">Sign in with Facebook</a><br><br>
      <a href="https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac">Sign in with GitHub</a>
    
    </code>
  3. Install Dependencies: Install Express and Passport:

    <code class="language-bash">npm install express passport --save</code>
  4. Express App: Create index.js:

    <code class="language-javascript">const express = require('express');
    const app = express();
    const port = process.env.PORT || 3000;
    
    app.get('/', (req, res) => res.sendFile('auth.html', { root: __dirname }));
    app.listen(port, () => console.log(`App listening on port ${port}`));</code>

    Run the app (node index.js) and verify http://localhost:3000 displays the HTML. Stop the app (Ctrl C).

Passport Configuration:

  1. Install Provider Strategies: Install Facebook and GitHub strategies:

    <code class="language-bash">npm install passport-facebook passport-github --save</code>
  2. Passport Setup in index.js:

    <code class="language-javascript">const passport = require('passport');
    app.use(passport.initialize());
    app.use(passport.session());
    
    app.get('/success', (req, res) => res.send("Successfully logged in!"));
    app.get('/error', (req, res) => res.send("Error logging in."));
    
    passport.serializeUser((user, done) => done(null, user));
    passport.deserializeUser((user, done) => done(null, user));</code>

Facebook Authentication:

  1. Create a Facebook App: Follow Facebook's instructions to create a new app and obtain your App ID and App Secret.

  2. Configure Facebook Strategy in index.js:

    <code class="language-javascript">const FacebookStrategy = require('passport-facebook').Strategy;
    const FACEBOOK_APP_ID = 'YOUR_FACEBOOK_APP_ID'; // Replace with your App ID
    const FACEBOOK_APP_SECRET = 'YOUR_FACEBOOK_APP_SECRET'; // Replace with your App Secret
    
    passport.use(new FacebookStrategy({
        clientID: FACEBOOK_APP_ID,
        clientSecret: FACEBOOK_APP_SECRET,
        callbackURL: "https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback",
        profileFields: ['id', 'displayName', 'photos', 'email'] //Optional: Specify fields to retrieve
    }, (accessToken, refreshToken, profile, done) => {
        done(null, profile);
    }));
    
    app.get('https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76', passport.authenticate('facebook'));
    app.get('https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback',
        passport.authenticate('facebook', { failureRedirect: '/error' }),
        (req, res) => res.redirect('/success')
    );</code>

    Remember to configure your Facebook app's valid OAuth redirect URIs to http://localhost:3000https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback.

GitHub Authentication:

  1. Create a GitHub App: Create a new GitHub app and obtain your Client ID and Client Secret.

  2. Configure GitHub Strategy in index.js:

    <code class="language-javascript">const GitHubStrategy = require('passport-github').Strategy;
    const GITHUB_CLIENT_ID = 'YOUR_GITHUB_CLIENT_ID'; // Replace with your Client ID
    const GITHUB_CLIENT_SECRET = 'YOUR_GITHUB_CLIENT_SECRET'; // Replace with your Client Secret
    
    passport.use(new GitHubStrategy({
        clientID: GITHUB_CLIENT_ID,
        clientSecret: GITHUB_CLIENT_SECRET,
        callbackURL: "https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac/callback"
    }, (accessToken, refreshToken, profile, done) => {
        done(null, profile);
    }));
    
    app.get('https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac', passport.authenticate('github'));
    app.get('https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac/callback',
        passport.authenticate('github', { failureRedirect: '/error' }),
        (req, res) => res.redirect('/success')
    );</code>

    Configure your GitHub app's authorization callback URL to http://localhost:3000https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac/callback.

Run the Application:

Start the server (node index.js) and test the Facebook and GitHub login links. The /success route will indicate successful authentication. Remember to replace placeholder IDs and secrets with your actual values. This provides a basic framework; error handling and user persistence in a database would be necessary for a production-ready application.

The above is the detailed content of Passport Authentication for Node.js Applications. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn