Authentication using Passport JS

Passport or PassportJS is NodeJS and ExpressJS Compatible middleware for authentication. Passport JS uses different different strategies to authenticate requests. This includes username and password authentication, Facebook or Twitter authentication and 500+ total strategies.

The purpose to use passport in NodeJS is to authenticate requests.


Install Passport JS

passport is available on npm as passport. Install passport and include passport in main app through module.

npm i passport

Passport JS is installed in NodeJS Application.


Install Passport Local

Now install passport-local strategy to authenticate username and password.

npm i passport-local

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

Configure Passport

  
const express=require('express');
let app=express();

const User=require('./models/user');
const db=require('./mdb');

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

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

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

passport.use('local', new LocalStrategy((username, password, done) => {
  
    User.findOne({ name: username }, (err, user) => { 
      if (err) { return done(err); }
      if (!user) { return done(null, null, { message: 'No user found!' }); }
      if (user.password !== password) {
        return done(null, null, { message: 'Username or password is incorrect!' });
      }
  
      return done(null, user, null);
    });
  }
));

function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
      next();
    } else {
      res.status(403).send('Forbidden');
    }
}