Passport Node Authentication

I've got to the point in creating a MEAN fullstack app that authentication is now on the agenda and i've decided to look closer at Passtport.js.

There are three ways that a user can be authenticated and that is by using local (using passport-local), basic (passport-http), or digest (passport-http).

Local

This using an identifier to get hold of the password and checks that this matches what has been entered.

Basic

This is similar to Local however it is stateless and does not require sessions to be used.

Digest

This is different from the two above in that it does not send the password as clear text.

Let's get hold of passport using NPM

npm install -g passport --save

I'll only be looking into Local and Basic for this blog.

Local

To use the passport-local module and create our express app

 var express = Require('express');
 var passport = Require('passport');
 var passportLocal = Require('passport-local');
 var app = express();

Now we can initialise the passport variable, start the session, and set our strategy.

 app.use(passport.initialize());
 app.use(passport.session());
 passport.use(new passportlocal.Strategy(...));

The strategy requires a function which will handle how to authenticate the username, and password passed to it. It will also have a callback (done) which will handle what to next (which will pass either null, or an object if it authenticates).

I'm going to put this in a seperate function

passport.use(new passportlocal.Strategy(confirmCredentials));
function confirmCredentials(username, password, done){
  if(username === password)
  {
      done(null, {
          id: 123,
          name: username
      });
  }
  else
  {
      done(null, null);
  }
}

this is a crude test as in the real world a call to the database for the user account ..etc.

When the user is authenticated a cookie session will be used to identify the session for each request thereafter. Passport does this by serializing and deserializing the user details from the cookie.

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

passport.deserializeUser(function(id, done){
    done(null, {id:id, name: id});
});

So in this example only the userid is kept in the cookie and used throughout the application.

As a result each request will have an isAuthenticated() function which means that this can be used in your view

  <body>
    <% if (!isAuthenticated) { %>
        <a href="/login">Login in Here</a>
    <% } else { %>
      <h1>Hello <%= user.name %></h1>
      <p>
      <a href="/logout">Logout</a>
      </p>
    <%  } %>
  </body>