Sling Academy
Home/Node.js/How to Use Passport in Express for Authentication

How to Use Passport in Express for Authentication

Last updated: December 28, 2023

Passport.js is an authentication middleware for Node.js that can be used in Express-based web applications. It is highly flexible and modular, offering a set of strategies to authenticate requests. In this guide, we’ll cover how to implement Passport in an Express application for user authentication.

Prerequisites

  • Node.js and npm installed
  • Basic knowledge of Express
  • An existing Express application

The Steps

Step 1: Install Passport and its Strategy

First, install Passport and the strategy of your choice (e.g., Local Strategy for username and password authentication) using npm:

npm install passport passport-local

Step 2: Create Passport Strategy

Configure the passport strategy for your application. For the Local Strategy, you’ll need to create a strategy that defines how users will be authenticated.

const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
    function(username, password, done) {
        // Your authentication logic goes here
    }
));

Step 3: Configure Express to Use Passport

Initialize Passport and configure it to manage sessions:

const express = require('express');
const passport = require('passport');
const session = require('express-session');

const app = express();

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

Step 4: Define Serialization and Deserialization

Serialize user information to the session and deserialize it when requests are made:

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    // Find the user using the id
});

Step 5: Set Up Authentication Routes

Create routes for login and registration using the Local Strategy:

app.post('/login', 
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash: true
    })
);

Complete Code Example

Below is an example of how you can put all the steps together to create a simple authentication mechanism using Express and Passport.

const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');

const app = express();

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
    function(username, password, done) {
        // User authentication logic goes here
    }
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    // User deserialization logic here
});

app.post('/login', 
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login',
        failureFlash: 'Invalid username or password.'
    })
);

app.listen(3000, function() {
    console.log('Server started on port 3000.');
});

Conclusion

In this article, we walked through the steps required to add authentication to an Express application using Passport.js. By following these steps, you can implement a range of authentication strategies catered to the needs of your project.

Next Article: Authentication and Authorization in Express.js with JWT

Previous Article: Node + Express + TypeScript: Create a simple REST API

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates