Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Passport Authentication for Node.js with MongoDB

$
0
0

What is Passport?

Passport is Express-consistent authentication middleware for Node.js. Passport can be convenient and simple. It will use be any Express based web application.

Passport supports many set of strategies like,
Local Strategy :- Username (req.body.username) and
Password (req.body.password),

Single sign-on using OAuth like,
Google
e.g passport.authenticate(‘google’);
Facebook,
Twitter,
GitHub,
LinkedIn
Instagram and more…

To get started we have to install passport into our node application, we will do via npm (Node Package Manager)

Open the command prompt in Windows, Linux, or Mac Terminal. I assume that your present working directory is application in which you are going to implement the passport.

Fire the below command in command prompt:

Package :  npm install passport –save

–save :- When we create node application it is necessary to generate package.json file. Install package then write –save which means package will go inside our package.json file.

How Passport Authentication Works?

Passport authentication request is called as passport.authenticate() and also specify which strategies is to be applied. The authenticate()’s function is used to connect middleware in Express application.

Example:

app.post('/login', passport.authenticate('local'),
    function(req, res) 
    { 
      // If this function gets called, authentication was successful. 
      // `req.user` contains the authenticated user. 

      res.redirect('/users/' + req.user.username); 
   });

Passport Authentication Usage

Passport local-strategies :-

Most broadly used in website authentication for users via username and password. So this authentication is done by passport local module.

So Open terminal and fire below command,

package: npm install passport-local –save

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

var passport = require(‘passport’),
    LocalStrategy = require(‘passport-local’).Strategy;

    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, { message: 'Incorrect username.' });
         }

             if (!user.validPassword(password))
        {

                return done(null, false, { message: 'Incorrect password.' });
              }
        return done(null, false, { message: 'Incorrect password.' });
        });
        }
    ));

There are 300+ strategies. Find the ones you want at: passportjs.org

Form :-

A form is placed on web page and allows users to enter their own credentials and can login.

<form action="/login" method="post">
      <div>
           <label>Username:</label>
           <input type="text" name="username"/>
      </div>    
      <div>
           <label>Password:</label>
           <input type="password" name="password"/>
      </div>
      <div>
           <input type="submit" value="Log In"/>
      </div>
</form>

Sessions :-

Passport will maintain constant login sessions.
In order to have continual work with session , serialized user must be use to session for authentication, and deserialized when consecutive requests are made.

Passport does not contain any condition on how your users’ records are stored. In place of that, you provide functions to Passport which implements needful serialize and deserialize logic. In a typical application, this will be done as easily as serializing the User ID and finding the user by ID when deserialize.

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

passport.deserializeUser(function(id, done) {
   User.findById(id, function (err, user) {
      done(err, user);
   });
});

Middleware :-

For the Passport used in our Express based application, it is necessary to configure it with the required middleware passport.initialize().

Your application uses persistent sessions of login so you can also use passport.session() middleware.

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 Request Or Routes:

POST method is used for submitted login form and passport using authenticate() with the use of local-strategy which will handle the login request.

app.post('/login',
    passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login', failureFlash: true })
);

successRedirect:- User enter their credential and it’s right.
FailureRedirect:- User enter their credential and it’s wrong.
FailureFlash:- Used for Messages (success message or error message)

Search all strategies :-

Strategies is available on passportjs.org
common strategies:-
Local-strategies for HTML Form,
OpenID, BrowserID
Facebook, Google, Twitter, etc..

Conclusion

That’s it ..

I personally feel to use this as it is easy to implement.

In Node.js Application passport is used for authentication purpose , but passport provides adjustability support so passport is definitely a better choice.

Passport provides robust authentication for Node.js


Viewing all articles
Browse latest Browse all 595

Trending Articles