Gergely Nemeth Co-Founder of RisingStack, EM at Uber

This is the 8th part of our Node.js tutorial series called Node Hero - in these chapters, you will learn how to get started with Node.js and deliver software products using it.

This Passport.js tutorial will walk you through the steps of setting up a local Node.js authentication strategy using Redis. You are going to learn how to create an authentication interface with Passport.js, where users will provide their usernames and passwords. Despite their complexity, authentication mechanisms can be easily implemented into Node.js.

Technologies to use

Before jumping head-first into our Passport.js authentication tutorial, let’s take a look at the technologies we are going to use in this chapter.

What is Passport.js?

Passport.js is a simple, unobtrusive Node.js authentication middleware for Node.js.

Passport.js can be dropped into any Express.js-based web application.

Passport is an authentication middleware for Node.js which we are going to use for session management.

What is Redis?

Redis is an open source (BSD licensed), in-memory data structure store, used as database, cache and message broker.

Redis is designed to support different kinds of abstract data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperlogs and geospatial indexes with radius queries.

We are going to store our user's session information in Redis, and not in the process's memory. This way our application will be a lot easier to scale.

The Demo Application which needs Authentication

For demonstration purposes, let’s build an application that does only the following:

exposes a login form,

exposes two protected pages: a profile page, secured notes



The Project Structure

You have already learned how to structure Node.js projects in the previous chapter of Node Hero, so let's use that knowledge!

We are going to use the following structure:

├── app | ├── authentication | ├── note | ├── user | ├── index.js | └── layout.hbs ├── config | └── index.js ├── index.js └── package.json

As you can see we will organize files and directories around features. We will have a user page, a note page, and some authentication related functionality.

(Download the full source code at https://github.com/RisingStack/nodehero-authentication)

The Node.js Authentication Flow

Our goal is to implement the following authentication flow into our application using Passport.js:

User enters username and password The application checks if they are matching If they are matching, it sends a Set-Cookie header that will be used to authenticate further pages When the user visits pages from the same domain, the previously set cookie will be added to all the requests Authenticate restricted pages with this cookie

To set up an authentication strategy like this in a Node.js app using Passport.js, follow these three steps:

Step 1: Setting up Express

We are going to use Express for the server framework - you can learn more on the topic by reading our Express tutorial.

// file:app/index.js const express = require('express') const passport = require('passport') const session = require('express-session') const RedisStore = require('connect-redis')(session) const app = express() app.use(session({ store: new RedisStore({ url: config.redisStore.url }), secret: config.redisStore.secret, resave: false, saveUninitialized: false })) app.use(passport.initialize()) app.use(passport.session())

What did we do here?

First of all, we required all the dependencies that the session management needs. After that we have created a new instance from the express-session module, which will store our sessions.

For the backing store, we are using Redis, but you can use any other, like MySQL or MongoDB.

Step 2: Setting up Passport.js for Node.js

Passport.js is a great example of a library using plugins. In this passport.js tutorial, we are adding the passport-local module which enables easy integration of a simple local authentication strategy using usernames and passwords.

For the sake of simplicity, in this example, we are not using a second backing store, but only an in-memory user instance. In real life applications, the findUser would look up a user in a database.

// file:app/authenticate/init.js const passport = require('passport') const bcrypt = require('bcrypt') const LocalStrategy = require('passport-local').Strategy const user = { username: 'test-user', passwordHash: 'bcrypt-hashed-password', id: 1 } passport.use(new LocalStrategy( (username, password, done) => { findUser(username, (err, user) => { if (err) { return done(err) } // User not found if (!user) { return done(null, false) } // Always use hashed passwords and fixed time comparison bcrypt.compare(password, user.passwordHash, (err, isValid) => { if (err) { return done(err) } if (!isValid) { return done(null, false) } return done(null, user) }) }) } ))

Once the findUser returns with our user object the only thing left is to compare the user's hashed password and the real password to see if there is a match. Always store passwords hashed and use fixed time comparison to avoid timing attacks.

If it is a match, we let the user in (by returning the user to passport - return done(null, user) ), if not we return an unauthorized error (by returning nothing to passport - return done(null) ).

Step 3: Adding Protected Endpoints

To add protected endpoints, we are leveraging the middleware pattern Express uses. For that, let's create the authentication middleware first:

// file:app/authentication/middleware.js function authenticationMiddleware () { return function (req, res, next) { if (req.isAuthenticated()) { return next() } res.redirect('/') } }

It only has only one role if the user is authenticated (has the right cookies); it simply calls the next middleware. Otherwise it redirects to the page where the user can log in.

Using it is as easy as adding a new middleware to the route definition.

// file:app/user/init.js const passport = require('passport') app.get('/profile', passport.authenticationMiddleware(), renderProfile)

Summary - Authentication with Passport.js

In this Passport.js tutorial, you have learned how to add a basic authentication to your Node.js application. Later on, you can extend it with different authentication strategies, like Facebook or Twitter. You can find more strategies at http://passportjs.org/.

The full, working example is on GitHub, you can take a look here: https://github.com/RisingStack/nodehero-authentication

Next up

The next chapter of Node Hero will be all about unit testing Node.js applications. You will learn concepts like unit testing, test pyramid, test doubles and a lot more!

Share your questions and feedbacks in the comment section.