OAuth2 with Passport.js: Secure Authentication for Node.js Applications

beginner
12 min

OAuth2 with Passport.js: Secure Authentication for Node.js Applications

Welcome to this comprehensive guide on implementing OAuth2 with Passport.js in your Node.js applications! In this tutorial, we'll explore how to use Passport.js to authenticate users using popular OAuth providers such as Google, Facebook, and GitHub.

🚀 What is OAuth2?

OAuth2 is an open standard for authorization, allowing a user to grant a third-party application limited access to their resources without sharing their credentials. It's a common method used for authentication in modern web applications.

📝 What is Passport.js?

Passport.js is an authentication middleware for Node.js, providing a simple yet flexible framework for handling authentication strategies, including OAuth2.

🎯 Setting Up Our Project

Let's start by creating a new Node.js project and installing the necessary dependencies:

bash
mkdir oauth-passport-demo cd oauth-passport-demo npm init -y npm install express passport passport-google-oauth20 passport-facebook passport-github2

📝 Creating the Basic Application Structure

Create a new file app.js and set up a basic Express server:

javascript
const express = require('express'); const app = express(); const port = 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); });

💡 Setting Up Passport.js

Initialize Passport.js, configure the strategy, and middleware for each provider:

javascript
const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth20').Strategy; const FacebookStrategy = require('passport-facebook').Strategy; const GitHubStrategy = require('passport-github2').Strategy; // Google, Facebook, and GitHub credentials // ... passport.use(new GoogleStrategy({ // Google credentials }, (accessToken, refreshToken, profile, done) => { // Verify the accessToken and save the user in your database done(null, profile); })); passport.use(new FacebookStrategy({ // Facebook credentials }, (accessToken, refreshToken, profile, done) => { // Verify the accessToken and save the user in your database done(null, profile); })); passport.use(new GitHubStrategy({ // GitHub credentials }, (accessToken, refreshToken, profile, done) => { // Verify the accessToken and save the user in your database done(null, profile); }));

💡 Setting Up Routes

Create routes for the login, callback, and logout endpoints:

javascript
app.get('/login/google', passport.authenticate('google', { scope: ['profile'] })); app.get('/login/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => { // Successfully authenticated, save the user session, and redirect }); app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email'] })); app.get('/login/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => { // Successfully authenticated, save the user session, and redirect }); app.get('/login/github', passport.authenticate('github')); app.get('/login/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (req, res) => { // Successfully authenticated, save the user session, and redirect });

💡 Setting Up Logout

Create a logout route to clear the session and redirect to the homepage:

javascript
app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); });

📝 Creating the Homepage

Create a simple homepage for the application:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>OAuth2 with Passport.js Demo</title> </head> <body> <h1>Welcome to OAuth2 with Passport.js Demo</h1> <!-- Add your navigation and content here --> </body> </html>

📝 Serving Static Files

To serve the homepage, set up Express to serve the public folder:

javascript
app.use(express.static('public'));

💡 Running the Application

Start the server and open your browser to http://localhost:3000:

bash
node app.js

🎯 Quiz

Quick Quiz
Question 1 of 1

What is OAuth2 used for?

Quick Quiz
Question 1 of 1

What is Passport.js?

Quick Quiz
Question 1 of 1

Which of the following is NOT a popular OAuth provider supported by Passport.js?

That's it for the OAuth2 with Passport.js tutorial! With this knowledge, you can now secure your Node.js applications by implementing authentication using popular OAuth providers. Happy coding! 🎉🎊🎓