Convert Figma logo to code with AI

jaredhanson logopassport

Simple, unobtrusive authentication for Node.js.

22,914
1,241
22,914
383

Top Related Projects

OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js

4,089

OAuth Proxy

15,556

The most scalable and customizable OpenID Certified™ OpenID Connect and OAuth Provider on the market. Become an OpenID Connect and OAuth2 Provider over night. Broad support for related RFCs. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters.

11,181

The most scalable and customizable identity server on the market. Replace your Homegrown, Auth0, Okta, Firebase with better UX and DX. Has all the tablestakes: Passkeys, Social Sign In, Multi-Factor Auth, SMS, SAML, TOTP, and more. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters.

Open source alternative to Auth0 / Firebase Auth / AWS Cognito

Quick Overview

Passport is a popular authentication middleware for Node.js. It's designed to be flexible and modular, supporting various authentication strategies including local, OAuth, and OpenID. Passport can be easily integrated into any Express-based web application.

Pros

  • Highly flexible and extensible with numerous authentication strategies
  • Easy integration with Express.js applications
  • Large and active community, providing support and contributing to the project
  • Simplifies the authentication process, reducing boilerplate code

Cons

  • Can be overwhelming for beginners due to its flexibility and numerous options
  • Documentation could be more comprehensive, especially for advanced use cases
  • Some strategies may require additional configuration or dependencies
  • Performance can be impacted when using multiple strategies simultaneously

Code Examples

  1. Basic local authentication setup:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));
  1. Implementing Google OAuth2 authentication:
const GoogleStrategy = require('passport-google-oauth20').Strategy;

passport.use(new GoogleStrategy({
    clientID: GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://www.example.com/auth/google/callback"
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));
  1. Serializing and deserializing user instances:
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

Getting Started

  1. Install Passport and the strategy you want to use:

    npm install passport passport-local
    
  2. Configure Passport and the strategy in your app:

    const express = require('express');
    const passport = require('passport');
    const LocalStrategy = require('passport-local').Strategy;
    
    const app = express();
    
    app.use(passport.initialize());
    app.use(passport.session());
    
    passport.use(new LocalStrategy(
      function(username, password, done) {
        // Implement user verification logic here
      }
    ));
    
    // Implement serializeUser and deserializeUser functions
    
    app.post('/login',
      passport.authenticate('local', { successRedirect: '/',
                                       failureRedirect: '/login' }));
    
  3. Implement the necessary routes and middleware in your application to handle authentication.

Competitor Comparisons

OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js

Pros of node-oidc-provider

  • Comprehensive OpenID Connect implementation
  • Built-in support for various OIDC flows and features
  • Highly configurable and customizable

Cons of node-oidc-provider

  • Steeper learning curve due to complexity
  • Less flexibility for non-OIDC authentication strategies
  • Requires more setup and configuration

Code Comparison

node-oidc-provider:

const Provider = require('oidc-provider');
const configuration = {
  // OIDC-specific configuration
};
const oidc = new Provider('http://localhost:3000', configuration);

Passport:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy((username, password, done) => {
  // Authentication logic
}));

Summary

node-oidc-provider is a specialized OIDC implementation offering comprehensive features and configurability, but with a steeper learning curve. Passport is a more general-purpose authentication middleware that's easier to set up for various strategies but less focused on OIDC specifics. Choose node-oidc-provider for dedicated OIDC implementations, and Passport for flexible, multi-strategy authentication needs.

4,089

OAuth Proxy

Pros of Grant

  • Supports a wider range of OAuth providers out-of-the-box (200+)
  • Simpler configuration and setup process
  • Built-in support for multiple OAuth flows (1.0, 2.0, OpenID Connect)

Cons of Grant

  • Less flexible for custom authentication strategies
  • Smaller community and ecosystem compared to Passport
  • Limited middleware support for different web frameworks

Code Comparison

Grant configuration:

const grant = Grant({
  defaults: {
    client_id: 'YOUR_CLIENT_ID',
    client_secret: 'YOUR_CLIENT_SECRET',
    callback: '/callback'
  },
  google: {
    scope: ['profile', 'email']
  }
})

Passport configuration:

const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
    clientID: 'YOUR_CLIENT_ID',
    clientSecret: 'YOUR_CLIENT_SECRET',
    callbackURL: '/auth/google/callback'
  },
  function(accessToken, refreshToken, profile, cb) {
    // Handle user authentication
  }
));

Both Grant and Passport are popular authentication libraries for Node.js applications. Grant offers simplicity and extensive provider support, while Passport provides more flexibility and a larger ecosystem. The choice between them depends on specific project requirements and developer preferences.

15,556

The most scalable and customizable OpenID Certified™ OpenID Connect and OAuth Provider on the market. Become an OpenID Connect and OAuth2 Provider over night. Broad support for related RFCs. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters.

Pros of Hydra

  • Comprehensive OAuth 2.0 and OpenID Connect server implementation
  • Scalable and designed for high-performance environments
  • Provides advanced security features like JSON Web Key rotation

Cons of Hydra

  • Steeper learning curve due to its comprehensive feature set
  • Requires more setup and configuration compared to Passport
  • May be overkill for simpler authentication needs

Code Comparison

Hydra (Go):

import "github.com/ory/hydra/client"

c := client.NewHTTPClientWithConfig(nil, &client.TransportConfig{
    Schemes:  []string{"http", "https"},
    Host:     "localhost:4444",
    BasePath: "/",
})

Passport (JavaScript):

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

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

Summary

Hydra is a more comprehensive OAuth 2.0 and OpenID Connect server, offering advanced features and scalability. It's suitable for complex, high-performance environments but requires more setup. Passport, on the other hand, is a simpler, more flexible authentication middleware for Node.js, easier to integrate but with fewer built-in features for OAuth and OpenID Connect. The choice between them depends on the specific requirements of your project and the level of complexity you're willing to manage.

11,181

The most scalable and customizable identity server on the market. Replace your Homegrown, Auth0, Okta, Firebase with better UX and DX. Has all the tablestakes: Passkeys, Social Sign In, Multi-Factor Auth, SMS, SAML, TOTP, and more. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters.

Pros of Kratos

  • More comprehensive identity and user management system
  • Built-in support for multi-factor authentication and account recovery
  • Designed for cloud-native environments with scalability in mind

Cons of Kratos

  • Steeper learning curve due to its more complex architecture
  • Requires additional infrastructure setup compared to Passport
  • Less flexibility for custom authentication strategies

Code Comparison

Passport (Node.js):

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

Kratos (Go):

r.HandleFunc("/auth/login", func(w http.ResponseWriter, r *http.Request) {
    flow := kratos.NewLoginFlow(w, r)
    // Handle login flow
})

Summary

Passport is a lightweight, flexible authentication middleware for Node.js, ideal for simple to moderately complex authentication needs. It's easy to integrate and supports various authentication strategies.

Kratos, on the other hand, is a more comprehensive identity and access management system. It offers advanced features like multi-factor authentication and account recovery out of the box, making it suitable for larger-scale applications with complex security requirements.

While Passport excels in simplicity and flexibility, Kratos provides a more robust, scalable solution for identity management in cloud-native environments. The choice between the two depends on the specific needs of your project and the level of complexity you're willing to manage.

Open source alternative to Auth0 / Firebase Auth / AWS Cognito

Pros of SuperTokens

  • Built-in session management and token handling
  • Comprehensive user authentication flows (sign up, sign in, password reset, etc.)
  • Self-hosted solution with more control over user data

Cons of SuperTokens

  • Steeper learning curve compared to Passport's simplicity
  • Less flexibility for custom authentication strategies
  • Smaller community and ecosystem

Code Comparison

SuperTokens (Node.js SDK):

import supertokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";

supertokens.init({
    appInfo: {
        apiDomain: "https://api.example.com",
        appName: "MyApp",
        websiteDomain: "https://example.com"
    },
    recipeList: [Session.init()]
});

Passport:

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

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

SuperTokens provides a more comprehensive out-of-the-box solution for authentication and session management, while Passport offers greater flexibility and simplicity for implementing custom authentication strategies. SuperTokens is self-hosted, giving more control over user data, but requires more setup and has a steeper learning curve. Passport has a larger ecosystem and community support, making it easier to find resources and integrate with various authentication providers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

passport banner

Passport

Passport is Express-compatible authentication middleware for Node.js.

Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies. Passport does not mount routes or assume any particular database schema, which maximizes flexibility and allows application-level decisions to be made by the developer. The API is simple: you provide Passport a request to authenticate, and Passport provides hooks for controlling what occurs when authentication succeeds or fails.


Sponsors

Simple Authentication
Make login our problem. Not yours.

Auth0 by Okta provides a simple and customizable login page to authenticate your users. You can dynamically add new capabilities to it - including social login, multi-factor authentication, or passkeys - without making changes to your app’s code.

We help protect your app and your users from attacks - defending your application from bot attacks and detecting runtime anomalies based on suspicious IPs, breached credentials, user context, and more.






Status: Build Coverage Dependencies

Install

$ npm install passport

Usage

Strategies

Passport uses the concept of strategies to authenticate requests. Strategies can range from verifying username and password credentials, delegated authentication using OAuth (for example, via Facebook or Twitter), or federated authentication using OpenID.

Before authenticating requests, the strategy (or strategies) used by an application must be configured.

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

There are 480+ strategies. Find the ones you want at: passportjs.org

Sessions

Passport will maintain persistent login sessions. In order for persistent sessions to work, the authenticated user must be serialized to the session, and deserialized when subsequent requests are made.

Passport does not impose any restrictions on how your user records are stored. Instead, you provide functions to Passport which implements the necessary serialization and deserialization logic. In a typical application, this will be as simple as serializing the user ID, and finding the user by ID when deserializing.

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

passport.deserializeUser(function(id, done) {
  User.findById(id, function (err, user) {
    done(err, user);
  });
});

Middleware

To use Passport in an Express or Connect-based application, configure it with the required passport.initialize() middleware. If your application uses persistent login sessions (recommended, but not required), passport.session() middleware must also be used.

var app = express();
app.use(require('serve-static')(__dirname + '/../../public'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

Authenticate Requests

Passport provides an authenticate() function, which is used as route middleware to authenticate requests.

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

Strategies

Passport has a comprehensive set of over 480 authentication strategies covering social networking, enterprise integration, API services, and more.

Search all strategies

There is a Strategy Search at passportjs.org

The following table lists commonly used strategies:

StrategyProtocolDeveloper
LocalHTML formJared Hanson
OpenIDOpenIDJared Hanson
BrowserIDBrowserIDJared Hanson
FacebookOAuth 2.0Jared Hanson
GoogleOpenIDJared Hanson
GoogleOAuth / OAuth 2.0Jared Hanson
TwitterOAuthJared Hanson
Azure Active DirectoryOAuth 2.0 / OpenID / SAMLAzure

Examples

Related Modules

The modules page on the wiki lists other useful modules that build upon or integrate with Passport.

License

The MIT License

Copyright (c) 2011-2021 Jared Hanson <https://www.jaredhanson.me/>

NPM DownloadsLast 30 Days