Socket
Socket
Sign inDemoInstall

passport

Package Overview
Dependencies
2
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    passport

Simple, unobtrusive authentication for Node.js.


Version published
Weekly downloads
2.5M
increased by1.89%
Maintainers
1
Install size
51.6 kB
Created
Weekly downloads
 

Package description

What is passport?

Passport is an authentication middleware for Node.js that can be used in any Express-based web application. It supports a comprehensive set of strategies to authenticate users using a username and password, Facebook, Twitter, and more.

What are passport's main functionalities?

Local Authentication

This feature allows you to set up local authentication where users can log in with a username and password. The LocalStrategy is used to authenticate users against a local database.

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);
    });
  }
));

OAuth Authentication

Passport can be used to authenticate users using OAuth providers like GitHub, Facebook, Twitter, etc. This code sample demonstrates how to authenticate users with GitHub using the GitHubStrategy.

passport.use(new GitHubStrategy({
    clientID: GITHUB_CLIENT_ID,
    clientSecret: GITHUB_CLIENT_SECRET,
    callbackURL: 'http://yourdomain.com/auth/github/callback'
  },
  function(accessToken, refreshToken, profile, cb) {
    User.findOrCreate({ githubId: profile.id }, function (err, user) {
      return cb(err, user);
    });
  }
));

JWT Authentication

Passport supports JSON Web Tokens (JWT) for securing API endpoints. The JwtStrategy is used to authenticate users based on a JWT token sent in the authorization header.

const JwtStrategy = require('passport-jwt').Strategy,
      ExtractJwt = require('passport-jwt').ExtractJwt;
let opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'secret';
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.sub}, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            return done(null, user);
        } else {
            return done(null, false);
            // or you could create a new account
        }
    });
}));

Other packages similar to passport

Readme

Source

passport banner

Passport

Build Coverage Quality Dependencies Tips

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 flexiblity 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.

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 300+ 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.

app.configure(function() {
  app.use(express.static(__dirname + '/../../public'));
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
});
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 300 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

Examples

  • For a complete, working example, refer to the login example included in passport-local.
  • Local Strategy: Refer to the following tutorials for setting up user authentication via LocalStrategy (passport-local)
  • Social Authentication: Refer to this tutorial for setting up various social authentication strategies, including a working example found on this repo.

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

Tests

$ npm install
$ make test

Credits

Supporters

This project is supported by Auth0

License

The MIT License

Copyright (c) 2011-2015 Jared Hanson <http://jaredhanson.net/>

Keywords

FAQs

Last updated on 21 May 2015

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc