Passport

0.7.0 · active · verified Sat Apr 18

Passport is an Express-compatible authentication middleware for Node.js. It provides a simple, unobtrusive way to authenticate requests through an extensible set of 'strategies' (plugins) for various authentication methods like username/password, OAuth, or OpenID. It focuses solely on authentication, allowing developers to make application-level decisions about database schemas and routing. The current stable version is 0.7.0, and it is actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up Passport with Express and a 'local' authentication strategy. It includes user serialization/deserialization for session management, a mock user database, and basic login/profile routes to show authentication in action. Users can access a protected profile route after logging in.

import express from 'express';
import session from 'express-session';
import passport from 'passport';
import { Strategy as LocalStrategy } from 'passport-local';

const app = express();

// Mock User database (in-memory)
const users = [{ id: '1', username: 'testuser', password: 'password123' }];

// Configure Passport local strategy
passport.use(new LocalStrategy(
  (username, password, done) => {
    const user = users.find(u => u.username === username);
    if (!user || user.password !== password) {
      return done(null, false, { message: 'Incorrect username or password.' });
    }
    return done(null, user);
  }
));

// Configure Passport session serialization/deserialization
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  const user = users.find(u => u.id === id);
  done(null, user);
});

// Setup Express middleware
app.use(session({
  secret: process.env.SESSION_SECRET ?? 'a-very-secret-key', // Use a strong secret in production
  resave: false,
  saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.urlencoded({ extended: false })); // For form parsing

// Example routes
app.get('/login', (req, res) => {
  res.send('<form action="/login" method="POST">Username: <input name="username"/><br/>Password: <input type="password" name="password"/><br/><button type="submit">Login</button></form>');
});

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

app.get('/profile', (req, res) => {
  if (!req.isAuthenticated()) {
    return res.redirect('/login');
  }
  res.send(`Welcome, ${req.user.username}! This is your profile.`);
});

app.listen(3000, () => console.log('Server running on port 3000'));

// To run this example:
// npm install express express-session passport passport-local
// Add "type": "module" to your package.json for ESM support.

view raw JSON →