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 doesn’t 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.

Install

$ npm install passport

Usage strategies

Passport uses the concept of strategies to authenticate requests. Strategies can include verifying the username and password credentials delegated authentication using OAuth, 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

The Passport package 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 doesn’t impose any restrictions on how your user records are stored. Instead, you provide functions to Passport, which then implements the necessary serialization and deserialization logic. In a typical application, this will be as simple as serializing the user ID, and then 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);

});

});

Head over to the official passport website to learn more about the project.