Home >Web Front-end >JS Tutorial >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-facebook
, passport-github
).Application Setup:
Project Initialization: Create a project directory and initialize a Node.js project:
<code class="language-bash">mkdir AuthApp cd AuthApp npm init -y</code>
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>
Install Dependencies: Install Express and Passport:
<code class="language-bash">npm install express passport --save</code>
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:
Install Provider Strategies: Install Facebook and GitHub strategies:
<code class="language-bash">npm install passport-facebook passport-github --save</code>
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:
Create a Facebook App: Follow Facebook's instructions to create a new app and obtain your App ID
and App Secret
.
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:
Create a GitHub App: Create a new GitHub app and obtain your Client ID
and Client Secret
.
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!