Auth ~ Passport - rohit120582sharma/Documentation GitHub Wiki

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

It provides an abstraction layer over logging in with various providers such as Facebook, Google, Github, Twitter and more.

Passport's sole purpose is to authenticate requests, which it does through an extensible set of plugins known as strategies.

The API is simple: you provide Passport a request to authenticate, and Passport provides hooks for controlling what occurs when authentication succeeds or fails.

If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.

References



Install

$ npm install passport
$ npm install cookie-session


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 Google or Facebook), or federated authentication using OpenID.

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

passport.use(new LocalStrategy(
    async (username, password, done) => {
        // Check if user exists in User collection
        let user = await User.findOne({ username: username });

        // If no
        if(!user) { return done(null, false); }

        // If yes, then verify the password
        if(!user.verifyPassword(password)) { return done(null, false); }

        // Return the actual user information
        return done(null, 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, passport.session() middleware must also be used.

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

Additionally it requires cookie-session module to store the session data on the client within a cookie. cookie-session does not require any database / resources on the server side and can simplify certain load-balanced scenarios. It can be used to store a "light" session and include an identifier to look up a database-backed secondary store to reduce database lookups.

var cookieSession = require('cookie-session');
app.use(cookieSession({
    maxAge: 24 * 60 * 60 * 1000,
    keys: [
        'cookiesessionsecretkey'
    ]
}));

Sessions

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

Here, 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(async (id, done) => {
    try {
        const user = await User.findById(id);
        done(null, user);
    } catch (err) {
        done(err);
    }
});

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('/');
    }
);
⚠️ **GitHub.com Fallback** ⚠️