This Passport.js tutorial will walk you through the steps of setting up a local Node.jsNode.js is an asynchronous event-driven JavaScript runtime and is the most effective when building scalable network applications. Node.js is free of locks, so there's no chance to dead-lock any process. authentication strategy using Redis with Express. You are going to learn how to create an authentication interface with Node.js & Passport.js, where users will provide their usernames and passwords. Despite their complexity, authentication mechanisms can be easily implemented into Node.js.
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.
See all chapters of the Node Hero tutorial series:
- Getting started with Node.js
- Using NPM
- Understanding async programming
- Your first Node.js HTTP server
- Node.js database tutorial
- Node.js request module tutorial
- Node.js project structure tutorial
- Node.js authentication using Passport.js[ this article ]
- Node.js unit testing tutorial
- Debugging Node.js applications
- Node.js Security Tutorial
- How to Deploy Node.js Applications
- Monitoring Node.js Applications
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 learnedhow to structure Node.js projectsin 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 athttps://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 ourExpress tutorial.
// file:app/index.jsconst 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 theexpress-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 thepassport-local
module which enables easy integration of a simple local authentication strategy using usernames and passwords.
For the sake of simplicity, in this Passport.js example, we are not using a second backing store, but only an in-memory user instance. In real life applications, thefindUser
would look up a user in a database.
// file:app/authenticate/init.jsconst passport = require('passport')const bcrypt = require('bcrypt')const LocalStrategy = require('passport-local').Strategyconst 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 thefindUser
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.jsfunction 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.jsconst passport = require('passport')app.get('/profile', passport.authenticationMiddleware(), renderProfile)
Summary – Authentication with Passport.js & Node.js Tutorial
In this Passport.js tutorial, you have learned how to set up a basic authentication with Passport in a Node.js application. Later on, you can extend it with different strategies, like Facebook authentication or Twitter authentication. You can find more strategies athttp://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 aboutunit testing Node.js applications. You will learn concepts like unit testing, test pyramid, test doubles and a lot more!
In case you have any questions on how to use passport js, let us know in the comments!
Consider RisingStack when you’re looking forNode.js consulting or development services.