CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-passport

Simple, unobtrusive authentication for Node.js

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-authentication.mddocs/

Core Authentication

Main authentication functionality providing strategy management, middleware creation, and request processing. This is the primary interface for integrating Passport into Express/Connect applications.

Capabilities

Authenticator Class

The core class providing all authentication functionality. The default export is a singleton instance, but you can create new instances using the constructor.

/**
 * Create a new Authenticator instance
 * @returns {Authenticator} New authenticator instance
 */
function Authenticator();

// Default singleton instance
const passport = require("passport");
// passport is an instance of Authenticator

// Create new instance
const { Authenticator } = require("passport");
const customPassport = new Authenticator();

Strategy Registration

Register and manage authentication strategies that define how authentication is performed.

/**
 * Register a strategy for later use when authenticating requests
 * @param {string} [name] - Name of the strategy (optional, uses strategy.name if not provided)
 * @param {Strategy} strategy - Authentication strategy instance
 * @returns {Authenticator} Returns this for chaining
 */
passport.use(name, strategy);
passport.use(strategy);

/**
 * Deregister a previously registered strategy
 * @param {string} name - Name of the strategy to remove
 * @returns {Authenticator} Returns this for chaining
 */
passport.unuse(name);

Usage Examples:

const LocalStrategy = require("passport-local").Strategy;
const GoogleStrategy = require("passport-google-oauth20").Strategy;

// Register strategy with default name
passport.use(new LocalStrategy(
  (username, password, done) => {
    // Verify credentials
    User.authenticate(username, password, done);
  }
));

// Register strategy with custom name
passport.use("admin-local", new LocalStrategy(
  (username, password, done) => {
    // Admin-specific authentication logic
    Admin.authenticate(username, password, done);
  }
));

// Register OAuth strategy
passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: "/auth/google/callback"
  },
  (accessToken, refreshToken, profile, done) => {
    // Handle OAuth profile
    User.findOrCreate({ googleId: profile.id }, done);
  }
));

Initialize Middleware

Create initialization middleware that prepares Passport for incoming requests.

/**
 * Create initialization middleware
 * @param {Object} [options] - Configuration options
 * @param {string} [options.userProperty='user'] - Property name for authenticated user on req
 * @param {boolean} [options.compat=true] - Enable compatibility layer for older strategies
 * @returns {Function} Express/Connect middleware function
 */
passport.initialize(options);

Usage Examples:

const express = require("express");
const app = express();

// Basic initialization
app.use(passport.initialize());

// With custom user property
app.use(passport.initialize({
  userProperty: "currentUser"
}));

// Disable compatibility layer
app.use(passport.initialize({
  compat: false
}));

Authentication Middleware

Create middleware that authenticates requests using specified strategies.

/**
 * Create authentication middleware
 * @param {string|string[]|Strategy} strategy - Strategy name(s) or instance(s)
 * @param {Object} [options] - Authentication options
 * @param {boolean} [options.session=true] - Save login state in session
 * @param {boolean} [options.keepSessionInfo=false] - Preserve session info during login
 * @param {string} [options.successRedirect] - URL to redirect after success
 * @param {string} [options.failureRedirect] - URL to redirect after failure
 * @param {boolean|string|Object} [options.successFlash=false] - Flash success messages
 * @param {boolean|string|Object} [options.failureFlash=false] - Flash failure messages
 * @param {boolean|string} [options.successMessage=false] - Store success message in session
 * @param {boolean|string} [options.failureMessage=false] - Store failure message in session
 * @param {boolean} [options.failWithError=false] - Pass errors to next middleware
 * @param {string} [options.assignProperty] - Assign user to custom request property
 * @param {boolean} [options.authInfo=true] - Include auth info in request
 * @param {string} [options.successReturnToOrRedirect] - Redirect to returnTo URL or specified URL
 * @param {Function} [callback] - Custom callback function
 * @returns {Function} Express/Connect middleware function
 */
passport.authenticate(strategy, options, callback);

Usage Examples:

// Basic form authentication
app.post("/login", 
  passport.authenticate("local", {
    successRedirect: "/dashboard",
    failureRedirect: "/login",
    failureFlash: true
  })
);

// API authentication without sessions
app.get("/api/users",
  passport.authenticate("bearer", { session: false }),
  (req, res) => {
    res.json(req.user);
  }
);

// Custom callback handling
app.post("/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) return next(err);
    if (!user) {
      return res.status(401).json({ error: info.message });
    }
    req.logIn(user, (err) => {
      if (err) return next(err);
      return res.json({ user: user });
    });
  })(req, res, next);
});

// Multiple strategy fallback
app.get("/api/protected",
  passport.authenticate(["bearer", "basic"], { session: false }),
  (req, res) => {
    res.json({ message: "Access granted" });
  }
);

// OAuth flow
app.get("/auth/google",
  passport.authenticate("google", { scope: ["profile", "email"] })
);

app.get("/auth/google/callback",
  passport.authenticate("google", {
    successRedirect: "/dashboard",
    failureRedirect: "/login"
  })
);

Authorization Middleware

Create middleware for third-party service authorization while preserving existing authentication.

/**
 * Create third-party service authorization middleware
 * @param {string|string[]|Strategy} strategy - Strategy name(s) or instance(s)
 * @param {Object} [options] - Authorization options (same as authenticate)
 * @param {Function} [callback] - Custom callback function
 * @returns {Function} Express/Connect middleware function
 */
passport.authorize(strategy, options, callback);

Usage Examples:

// Connect Twitter account to existing user
app.get("/connect/twitter",
  passport.authorize("twitter", { failureRedirect: "/account" })
);

app.get("/connect/twitter/callback",
  passport.authorize("twitter", { failureRedirect: "/account" }),
  (req, res) => {
    // req.account contains Twitter account info
    // req.user contains existing logged-in user
    req.user.twitter = req.account;
    req.user.save(() => {
      res.redirect("/account");
    });
  }
);

Session Middleware

Create middleware for session-based authentication restoration.

/**
 * Restore login state from session
 * @param {Object} [options] - Session options
 * @param {boolean} [options.pauseStream=false] - Pause request stream during deserialization
 * @returns {Function} Express/Connect middleware function
 */
passport.session(options);

Usage Examples:

const express = require("express");
const session = require("express-session");
const app = express();

// Complete session setup
app.use(session({
  secret: "keyboard cat",
  resave: false,
  saveUninitialized: false
}));

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

// With stream pausing for body parsing
app.use(passport.session({
  pauseStream: true
}));

Framework Integration

Adapt Passport to work with different web frameworks (defaults to Connect/Express).

/**
 * Adapt authenticator to work with specific framework
 * @param {Object} fw - Framework adapter object
 * @returns {Authenticator} Returns this for chaining
 */
passport.framework(fw);

Usage Examples:

// Custom framework adapter
const customFramework = {
  initialize: (passport, options) => {
    // Return framework-specific initialize middleware
    return (req, res, next) => {
      // Framework-specific initialization logic
      next();
    };
  },
  authenticate: (passport, name, options, callback) => {
    // Return framework-specific authenticate middleware
    return (req, res, next) => {
      // Framework-specific authentication logic
    };
  }
};

passport.framework(customFramework);

Error Handling

Passport uses a specific error class for authentication failures:

/**
 * Authentication error class
 * @param {string} message - Error message
 * @param {number} [status=401] - HTTP status code
 */
class AuthenticationError extends Error {
  constructor(message, status);
  name: "AuthenticationError";
  message: string;
  status: number;
}

Authentication errors can be handled through the failWithError option or custom callbacks:

// Handle errors in error middleware
app.post("/login",
  passport.authenticate("local", { failWithError: true }),
  (req, res) => {
    res.redirect("/dashboard");
  },
  (err, req, res, next) => {
    if (err.name === "AuthenticationError") {
      res.status(err.status).json({ error: err.message });
    } else {
      next(err);
    }
  }
);

Install with Tessl CLI

npx tessl i tessl/npm-passport

docs

core-authentication.md

index.md

session-management.md

strategy-development.md

tile.json