Monday, February 5, 2018

Local Authentication Using Passport in Node.js

In Passport Authentication for Node.js Applications, we talked about authentication using Passport as it relates to social login (Google, Facebook, GitHub, etc.). In this article, we’ll see how we can use Passport for local authentication with a MongoDB back end.

All of the code from this article is available for download on GitHub.

Prerequisites

  • Node.js — Download and install Node.js.
  • MongoDB — Download and install MongoDB Community Server. Follow the instructions for your OS. Note, if you’re using Ubuntu, this guide can help you get Mongo up and running.

Creating the Project

Once all of the prerequisite software is set up, we can get started.

We’ll begin by creating the folder for our app and then accessing that folder on the terminal:

mkdir AuthApp
cd AuthApp

To create the node app, we’ll use the following command:

npm init

You’ll be prompted to provide some information for Node’s package.json. Just hit enter until the end to leave the default configuration.

HTML

Next, we’ll need a form with username and password inputs as well as a Submit button. Let’s do that! Create a file called auth.html in the root folder of your app, with the following contents:

<html>
  <body>
    <form action="/" method="post">
      <div>
        <label>Username:</label>
        <input type="text" name="username" />
        <br/>
      </div>
      <div>
        <label>Password:</label>
        <input type="password" name="password" />
      </div>
      <div>
        <input type="submit" value="Submit" />
      </div>
    </form>
  </body>
</html>

That will do just fine.

Setting up Express

Now we need to install Express, of course. Go to the terminal and write this command:

npm install express --save

We’ll also need to install the body-parser middleware which is used to parse the request body that Passport uses to authenticate the user.

Let’s do that. Run the following command:

npm install body-parser --save

When that’s done, create a file index.js in the root folder of your app and add the following content to it:

/*  EXPRESS SETUP  */

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

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => res.sendFile('auth.html', { root : __dirname}));

const port = process.env.PORT || 3000;
app.listen(port , () => console.log('App listening on port ' + port));

We’re doing almost the same as in the previous tutorial. First we require Express and create our Express app by calling [express()](http://expressjs.com/en/api.html#express). The next line is the only difference with our previous Express setup. We’ll need the body-parser middleware this time, in order for authentication to work correctly. Then we declare the route for the home page of our app. There we send the HTML file we created to the client accessing that route. Then, we use process.env.PORT to set the port to the environment port variable if it exists. Otherwise, we’ll default to 3000, which is the port we’ll be using locally. This gives you enough flexibility to switch from development, directly to a production environment where the port might be set by a service provider like, for instance, Heroku. Right below we called [app.listen()](http://expressjs.com/en/api.html#app.listen) with the port variable we set up and a simple log to let us know that it’s all working fine and on which port is the app listening.

That’s all for the Express setup. Now we have to set up Passport, exactly as we did the last time. I’ll show you how to do that in case you didn’t read the previous tutorial.

Setting up Passport

First, we install passport with the following command:

npm install passport --save

Then, add the following lines at the bottom of your index.js file:

/*  PASSPORT SETUP  */

const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());

app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));

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

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

Here, we require passport and initialize it along with its session authentication middleware, directly inside our Express app. Then, we set up the '/success' and '/error' routes which will render a message telling us how the authentication went. If it succeeds, we’re going to show the username parameter, which we’ll pass to the request. We’re using the same syntax for our last route, only this time instead of using [res.SendFile()](http://expressjs.com/en/api.html#res.sendFile) we’re using [res.send()](http://expressjs.com/en/api.html#res.send), which will render the given string as text/html on the browser. Then we’re using serializeUser and deserializeUser callbacks. The first one will be invoked on authentication, and its job is to serialize the user instance with the information we pass to it (the user ID in this case) and store it in the session via a cookie. The second one will be invoked every subsequent request to deserialize the instance, providing it the unique cookie identifier as a “credential”. You can read more about that in the Passprot documentation.

As a side note, this very simple sample app of ours will work just fine without deserializeUser, but it kills the purpose of keeping a session, which is by all means something you’ll need in every app that requires login.

Continue reading %Local Authentication Using Passport in Node.js%


by Paul Orac via SitePoint

No comments:

Post a Comment