Monday, February 5, 2018

Passport Authentication for Node.js Applications

In this tutorial, we'll be implementing authentication via Facebook and GitHub in a Node.js web application. For this, we'll be using Passport, an authentication middleware for Node.js. Passport supports authentication with OpenId/OAuth providers.

Express Web App

Before getting started, make sure you have Node.js installed on your machine.

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.

Next, we'll need an HTML file to send to the client. Create a file called auth.html in the root folder of your app, with the following contents:

<html>
  <head>
    <title>Node.js OAuth</title>
  </head>
  <body>
    <a href=auth/facebook>Sign in with Facebook</a>
    <br></br>
    <a href=auth/github>Sign in with Github</a>
  </body>
</html>

That's all the HTML we'll need for this tutorial.

You’ll also require Express, a framework for building web apps that’s inspired by Ruby's Sinatra. In order to install Express, from the terminal type the following command:

npm install express --save

Once you’ve done that, it's time to write some code.

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();

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));

In the code above, we require Express and create our Express app by calling express(). Then we declare the route for the home page of our app. There we send the HTML file we’ve 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 call 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.

Now we should start our app to make sure all is working correctly. Simply write the following command on the terminal:

node index.js

You should see the message: App listening on port 3000. If that’s not the case, you probably missed a step. Go back and try again.

Moving on, let's see if our page is being served to the client. Go to your web browser and navigate to http://localhost:3000.

If you can see the page we created in auth.html, we're good to go.

Head back to the terminal and stop the app with ctrl + c. So remember, when I say start the app, you write node index.js, and when I say stop the app, you do ctrl + c. Clear? Good, you've just been programmed :-)

Setting up Passport

As you'll soon come to realize, Passport makes it a breeze to provide authentication for our users. Let's install Passport with the following command:

npm install passport --save

Now we have to set up Passport. Add the following code at the bottom of the index.js file:

/*  PASSPORT SETUP  */

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

app.get('/success', (req, res) => res.send("You have successfully logged in"));
app.get('/error', (req, res) => res.send("error logging in"));

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

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
});

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. It’s 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 in 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 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 Passport 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 something you'll need in every app that requires login.

That's all for the actual Passport setup. Now we can finally get onto business.

Continue reading %Passport Authentication for Node.js Applications%


by Paul Orac via SitePoint

No comments:

Post a Comment