Simple, unobtrusive authentication for Node.js.

Overview

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

LoginRadius is built for the developer community to integrate robust Authentication and Single Sign-On in just a few lines of code.
FREE Signup


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:

Strategy Protocol Developer
Local HTML form Jared Hanson
OpenID OpenID Jared Hanson
BrowserID BrowserID Jared Hanson
Facebook OAuth 2.0 Jared Hanson
Google OpenID Jared Hanson
Google OAuth / OAuth 2.0 Jared Hanson
Twitter OAuth Jared Hanson
Azure Active Directory OAuth 2.0 / OpenID / SAML Azure

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-2019 Jared Hanson <http://jaredhanson.net/>

Comments
  • 0.3.0 is not working

    0.3.0 is not working

    Hey people,

    Just for your information, your latest version (0.3.3) is not working for me.

    I am using its simpleLocalStrategy and getting user is undefined.

    so I reverted to previous release (0.2.2) which is working for me.

    opened by 4auvar 60
  • Route with passport.authenticate results in bad request

    Route with passport.authenticate results in bad request

    I'm using passportjs with expressjs 4.12 and I'm having a bad request when trying to limit access to a route.

    The following code gives a bad request

    router.get('/users', passport.authenticate('local'), function(req, res) {
            res.json({ currentUser: req.user });
    });
    

    But this one works and gives me the logged in user.

    router.get('/users', function(req, res) {
            res.json({ currentUser: req.user });
    });
    

    What could be wrong in the setup? The login system seems to work, the user is saved in the request session, the serialize/deserialize function from passport are called when executing the second code (without the access check).

    opened by tleunen 33
  • `req.isAuthenticated()` returning false immediately after login

    `req.isAuthenticated()` returning false immediately after login

    StackOverflow question here.

    I've been fighting for quite awhile with this bug: immediately after the user authenticates with, say, Google, req.isAuthenticated() is returning false. I'm persisting sessions to a Postgres DB, which seems to be working fine. It's just the call to isAuthenticated which leads me to wonder if my Passport configuration might be wrong, or something.

    My code for the callback looks like:

    const redirects = {
      successRedirect: '/success',
      failureRedirect: '/failure'
    };
    app.get('/auth/google/callback', passport.authenticate('google', redirects));
    

    My very last middleware logs the value of req.isAuthenticated(). It logs false when Google redirects back to my page, but if the user manually refreshes then it returns true.

    Here are detailed logs of the logging in process:

    # this is the first request to the login page. Not logged in yet.
    4:59:54 PM web.1 |  -----New request-----
    4:59:54 PM web.1 |  route: /login authenticated: false
    
    # they've clicked the link to `/login`, and are immediately forwarded to Google
    4:59:59 PM web.1 |  -----New request-----
    
    # they've granted across through Google; Google redirects back to app.
    # Using the Google profile, we get the user's account from the user account table
    5:00:06 PM web.1 |  -----New request-----
    5:00:06 PM web.1 |  about to fetch from DB
    5:00:07 PM web.1 |  retrieved user from DB
    
    # redirection to the success page...`authenticated` is false? It should now be true!
    5:00:07 PM web.1 |  -----New request-----
    5:00:07 PM web.1 |  route: /success authenticated: false
    
    # here's a manual refresh...now they're showing as authenticated
    5:05:34 PM web.1 |  successful deserialize
    5:05:34 PM web.1 |  -----New request-----
    5:05:34 PM web.1 |  route: /success authenticated: true
    

    It looks like deserialize isn't being called when Google redirects back to my app; could that be the source of the issue?

    Source code:

    opened by jamesplease 32
  • Pass req to serialize/deserialize callbacks

    Pass req to serialize/deserialize callbacks

    Passing the req object allows for greater flexibility when serializing/deserializing users. This comes in really handy when the action is altered based on the request.

    For example, in my setup, depending on the domain in which the request comes through, it uses a different database configuration. Without the req object, I have no way of knowing what domain it is.

    It should all be backwards compatible with existing solutions. Let me know otherwise.

    Thanks for all of your work on passport!

    opened by camshaft 21
  • Pause request stream during (potentially async) deserialiseUser call

    Pause request stream during (potentially async) deserialiseUser call

    Because the deserializeUser is treated as connect middleware and may be followed by other middleware that is listening for request events, the request stream events should be buffered until all middleware is called. Without pausing the request, middleware that pipes the incoming request (e.g. file upload, body parsing, proxy middleware, etc.) may miss data or end events.

    opened by tschaub 21
  • The future of Passport.js

    The future of Passport.js

    Hey :wave:

    Passport.js still remains the recommended way by many to implement authentication in Node.js applications. There are a lot of businesses that rely on this and there are also a lot of newcomers to Node being directed to this library by various videos and blog articles.

    I noticed that there hasn't been a commit in 7 months and this has led me to wonder about the future of the project.

    There are currently, as of writing, 308 open issues and 30 open pull requests. Quite a few of these issues and pull requests span back months or years and many don't have any responses.

    I understand maintaining an open source library of this size and importance is tiresome work but I just wonder what the plans are for the future? How should we collectively go about triaging these issues and working our way through the open PRs?

    Is there also work to be done on improving the documentation for the project? Last time I implemented Passport.js in a project I stumbled across this alternate manual, the existence of this probably indicates the official documentation could do with some work.

    I also found similar sentiment in the /r/node Reddit thread about the alternate documentation.

    Thanks, Luke

    documentation website discussion 
    opened by Glazy 17
  • URGENT ISSUE NPM 0.5.1 BREAKING CHANGE PUBLISHED!??! (Error seen: 'middleware not in use')

    URGENT ISSUE NPM 0.5.1 BREAKING CHANGE PUBLISHED!??! (Error seen: 'middleware not in use')

    Hi,

    Maximum strangeness. The latest version on npm is 0.5.1 with breaking changes (e.g. req._passport isn't defined, and therefore we got 'middleware not in use' related errors as-of-today's recent builds).

    Can someone take a look at this urgently please, before more people are affected?

    Thanks, John

    bug 
    opened by jfstephe 16
  • req.isAuthenticated occasionally fails - race condition?

    req.isAuthenticated occasionally fails - race condition?

    I have set up passport to use a custom authentication scheme, but for arguments sake, imagine it authenticates any user to the app. I have a 'landing' page with a login button that issues a post, handled as follows:

    app.post('/:id/landing', function (req, res, next) {
      passport.authenticate('myAuth', function (err, user) {
        if (err || !user) {
          return res.redirect('/' + req.params.id + '/landing' + req.body.redirectTo);
        } else {
          req.logIn(user, function () {
            return res.redirect('/' + req.params.id + '/' + req.body.redirectTo);
          });
        }
      })(req, res, next);
    });
    

    later, a route handler matches the redirect:

    app.all('/:id/', function (req, res) {
      if (req.isAuthenticated()) {
        res.sendFile('index.html', {root: __dirname + '/../frontend/'});
      } else {
        // Instead of redirecting to /landing, simply render it.
        // this gets round safari issue with losing url fragments during a redirect:
        // https://bugs.webkit.org/show_bug.cgi?id=24175
        //
        res.render('landing', {message: '', previousID: '/' + req.params.id});
      }
    });
    

    9 times out of ten, this all works fine, but occasionally req.isAuthenticated will return false. If I put some logging in, I can see that before the redirect I have a valid req.user object, but then in the second route handler following the redirect, req.user is undefined. Sometimes it works, sometimes it doesn't! (When it does work, req.user IS defined in the second route handler) Is this issue the same as others have reported around the user not being serialised correctly?

    opened by benheymink 15
  • Fix express deprecated msg - Use res.redirect(status, url) instead

    Fix express deprecated msg - Use res.redirect(status, url) instead

    In expressjs 4.6.1 I am getting this deprecation warning:

    "express deprecated res.redirect(ur, status): Use res.redirect(status, url) instead node_modules/passport/lib/middleware/authenticate.js:294:15"

    So I fixed it for you! ;)

    Note: my editor also removed excess spaces automatically - sorry about all the changes below - line 294 is the only real change.

    opened by dstroot 15
  • req.logout doesn't remove session in sessionStore with connect-redis

    req.logout doesn't remove session in sessionStore with connect-redis

    I'm using passport-local. I have a logout method that calls req.logout to end the session. The problem is it doesn't clear req.session so connect saves a bogus session entry to redis when req.send is called:

    Before logout:

    1. "{"cookie":{"originalMaxAge":259200000,"expires":"2014-03-21T22:03:55.265Z","httpOnly":true,"path":"/"},"passport":{"user":"bn"}}"

    After logout:

    1. "{"cookie":{"originalMaxAge":259200000,"expires":"2014-03-21T22:04:01.148Z","httpOnly":true,"path":"/"},"passport":{}}"

    Is this something we're expected to take care of ourselves?

    opened by 2fours 15
  • Passport.js does not work with cookieSession (Express.js)

    Passport.js does not work with cookieSession (Express.js)

    I'm using Passport to log in with Facebook or Twitter into my service. Since MemoryStore is not intended for production and I'm not going to store much information into the session, I wanted to use cookieSession, but it doesn't work:

    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.cookieSession({ secret: 'keyboard cat', cookie: {maxAge: 60 * 60} }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
    

    It works as expected if I repace cookieSession() with session():

    app.use(express.session({ secret: 'keyboard cat' }));
    
    opened by eneko89 15
  • Passport SAML is always chosen first by NestJS Passport, no matter the order

    Passport SAML is always chosen first by NestJS Passport, no matter the order

    When using NestJS and Passport to authenticate users, SAML will always be chosen as the first strategy. I'm providing passport several strategies as a fallback, but if SAML is somewhere in that array, it will always be the first to be checked.

    Expected behavior

    I expect that Passport will try to use the provided stragies in the order they are passed.

    Actual behavior

    If saml is somewhere defined in the array of strategies passed on to passport. The saml strategy will always be the first to be tried, regardless of the actual position in the passed array. It can be defined as the last strategy in the array and it will still be the first strategy to be tried.

    Steps to reproduce

    1. Use NestJS and Passport for authentication
    2. Create SAML Strategy
    3. Provide passport basic and saml as a strategy
    4. Start the authentication process
    5. Notice that you will be redirected to SAML accessUrl

    Environment

    Environment

    Node.js version: 18.10.0 passport version: ^0.4.1

    opened by Fakerinc 7
  • Look for 500 error code

    Look for 500 error code

    Hi Team,

    When I upgrade my passport version 0.4.0 to 0.6.0 my service deployment getting failed in AWS. Getting 500 error code and unhealthy in target group.

    opened by bsarankumar 3
  • "Error: failed to deserialize user out of session"

    I am getting "Error: failed to deserialize user out of session" - the problem is that this generates 500 server error and I can't present a nice page to the user to say "please log in again". How can I work around this?

    The issue is related to https://github.com/LaunchAcademy/generator-engage/issues/122 and https://github.com/jaredhanson/passport/issues/6 - what happens is that I have a bad cookie with User ID that does not exist. In deserializeUser my function User.findOne correctly returns an error and I pass this to Passport's done/callback with false as others have done before me. But Passport still creates a 500 error instead of redirecting back to the login page. I guess I could do some sort of a hack and try to clear the cookie in the deserializeUser but feels hacky.

    What is the way to solve this? Is there a way to instruct Passport to forward the request back to the login page in case of an error in deserializeUser rather than generate server error 500?? It's not that 500 is ugly but it also prevents user from logging on until the cookie is cleared manually.

    My code below for reference

    passport.deserializeUser(function(user, cb) {
      process.nextTick(async function() { 
        var usr = false;
        usr = await User.findOne(null, user.id)
          .catch(err => 
            cb(err, false)); // this gets triggered by User.findOne as the user.id is non-existent in the DB
        return cb(null, usr || false);
      });
    });
    

    I have tried returning cb(err) or cb(err, null) etc but none worked

    opened by molt2020 0
  • Session is reconstructed completely after login method

    Session is reconstructed completely after login method

    Are you looking for help? Yes

    Is this a security issue? No

    I set the socketId to session before authorizing the user but after .login() was called on the passport, the socketId is deleted and every other part of the session object was rewritten ( It seems passports is trying to create session object again with it's own related data).

    I use passport, passport-google, and passport-local to provide simple authentication on nestjs. I set the socketId on middleware to announce the user after the authorization, process is done and close the google auth window on client.

    Expected behavior

    On version 0.4.1 The socketId still exists after user is logged in and I can notify user that you are authenticated but in this version socketId does not exists or any other session data that had been added before login.

    Steps to reproduce

    For reproduction you need to upgrade the Passport to version 6.0.0 and set any data to session.

    Before the .login() method call thissession looks like:

    cookie:  {path: '/', _expires: Mon Dec 20 2040 21:39:35 GMT+0400 (GMT+04:00), originalMaxAge: 3000000000000, httpOnly: true}
    test: 'Monaliza'
    socketId: 'Ejy-bm0QelhLvS7jAAAB'
    id: '0513aa87-2376-4f42-b42e-f3fb2fb3540b'
    

    After the .login() method call session looks like:

    cookie: {path: '/', _expires: Mon Dec 20 2117 21:42:15 GMT+0400 (GMT+04:00), originalMaxAge: 3000000000000, httpOnly: true}
    passport: {user: 1}
    id: dca6-4a00-8840-d4ff4e392355'
    

    I checked every dependency problem and I'm sure problem is related to the Passport.

    Environment

    opened by me-dira 1
  • Fix #904, Required regenerate and save API (req.session.regenerate is not a function since upgrade to 0.6.0)

    Fix #904, Required regenerate and save API (req.session.regenerate is not a function since upgrade to 0.6.0)

    Background RE: #904

    Using [email protected], [email protected] with the [email protected] module to login with Github, the application throws the following error message:

    TypeError: req.session.regenerate is not a function at SessionManager.logIn
    

    Feature

    Utilize the Delegate Pattern and default to an empty implementation so that the code does not throw an error.

    Checklist

    • [ x ] I have read the CONTRIBUTING guidelines.
    • [ x ] I have added test cases which verify the correct operation of this feature or patch.
    • [ x ] I have added documentation pertaining to this feature or patch.
    • [ x ] The automated test suite ($ make test) executes successfully.
    • [ x ] The automated code linting ($ make lint) executes successfully. (NOTE: Lint errors are with code not touched by this PR)
    opened by joeyguerra 0
Owner
Jared Hanson
I make things with computers.
Jared Hanson
Authentication solution for Express

Lockit Lockit is an authentication solution for Express. Check out the demo. It consists of multiple single purpose modules: lockit-login lockit-signu

Mirco Zeiss 445 Dec 28, 2022
A small project with 3 accounts mapped to 3 resources using auth0 as an authentication service.

Auth0WithExpressJS Quickstart install dependencies for backend and start backend cd Auth0WithExpressJS\Back && npm start install dependencies for fron

RYMND 16 Aug 21, 2021
Role based authentication for NodeJS and ExpressJS

Authentication service made for ExpressJS and MongoDB using JWT. We tried to make it as clean and structured as possible. We also provide this documentation on how to install and integrate it with your own application.

null 4 Oct 3, 2021
An easy to use authentication system that can easily be built in to your Express + HBS web apps.

yoAuth An easy to use authentication system that can easily be built in to your Express + HBS web apps. Currently only supports local authentication,

null 2 Jan 21, 2022
Building an API on nodejs with registration system, authentication, CRUD of projects and tasks.

api-token-express Building an API on nodejs with registration system, authentication, CRUD of projects and tasks. API endpoints POST { "username":

MrDiniz 4 Jan 15, 2022
Edge-side GitHub authentication

cloudflare-workers-github-auth Edge-side GitHub authentication example. Requirements node.js (v16.13.1 or later) Installation Clone this repository an

Yoshiaki Sugimoto 7 Feb 21, 2022
node.js auth package (password, facebook, & more) for Connect and Express apps

everyauth Authentication and authorization (password, facebook, & more) for your node.js Connect and Express apps. There is a NodeTuts screencast of e

Brian Noguchi 3.5k Dec 17, 2022
node.js/express module to authenticate users without password

Passwordless Passwordless is a modern node.js module for Express that allows authentication and authorization without passwords by simply sending one-

Florian Heinemann 2k Dec 14, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser

Node-Casbin News: still worry about how to write the correct node-casbin policy? Casbin online editor is coming to help! node-casbin is a powerful and

Casbin 2.1k Dec 27, 2022
This project shows how you can easily jwt protect your endpoints in web api apps built with node js.

JWT Protected NodeJs API This project shows how you can easily jwt protect your endpoints in web api apps built with node js. It is an easy and simple

Cihat Girgin 3 Oct 19, 2021
Node-sodium-jwt - Fast sodium-based crypto for signing and verifying json web tokens (JWT)

node-sodium-jwt Features Fast sodium-based crypto for hashing json web tokens (JWT) Relies on sodium-native to perform crypto. Built with TypeScript f

Olivier Louvignes 1 Jan 3, 2022
Simple express request logger middleware for jsout.

jsout-express Simple express request logger middleware for jsout. Installation npm i jsout jsout-express -D Example Usage import {logger} from 'jsout'

Marc H. Weiner 2 Feb 25, 2022
Simple JWT Auth With TRPC prisma & next

Simple JWT Auth With TRPC prisma & next A sample JWT authentication using prisma, @trpc/server @trpc/client @trpc/react in Next.js Simple Usage copy .

Aris Riswanto 4 Aug 23, 2022
Unobtrusive page transitions with jQuery.

smoothState.js smoothState.js is a jQuery plugin that progressively enhances page loads to give us control over page transitions. If the user's browse

Miguel Pérez 4.5k Dec 21, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
The authentication-server is a node app that handles user registration, authentication & authorization with JWT.

Authentication Server The authentication-server is a node app that handles user registration, authentication & authorization with JWT. Here is the REP

Oğuz Çolak 18 Jul 24, 2022
We are creating a Library that would ensure developers do not reinvent the wheel anymore as far as Authentication is concerned. Developers can easily register and download authentication codes that suits their need at any point.

#AuthWiki Resource Product Documentation Figma Database Schema First Presentation Live Link API Documentation Individual Contributions User Activity U

Zuri Training 17 Dec 2, 2022
Parcel Next JS - A simple website with Authentication and basic API calls to a backend system.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Subham Roy 1 Jan 2, 2022