Authenticate Users With Node ExpressJS and Passport.js
Many Node.js applications require users to authenticate in order to access private content. The authentication process must be both functional and secure, and creating one from scratch can be lengthy and cumbersome. Because of this, most modern-day developers opt to use trusted libraries or outside services. Passport.js is a popular Express middleware specifically created to facilitate the login process. It is flexible, trusted by many organizations worldwide, and easy to integrate into your ExpressJS code.
In this tutorial we’ll:
- Create a login form for a Node application using Passport
- Use the session authentication strategy with Passport
- Connect Passport to a MongoDB database to store user data
- Authorize only logged-in users to access a page
By the end of this tutorial, you will learn how to create a functional login page complete with authentication and authorization.
This tutorial is part 7 of 7 tutorials that walk through using Express.js for user authentication.
Goal
Create an application that performs basic authentication and authorization tasks.
Prerequisites
- What Is the Difference between Authorization and Authentication?
- Process a Login Form with ExpressJS
- Setup Express Session Authentication
Passport.js strategies
Passport is a library of authentication functions that is adaptable to the needs of most applications. What makes Passport so flexible? The main reason is that developers can choose from a cornucopia of implementation strategies.
Passport strategies are separate modules created to suit individual means of authentication. Available Passport strategies include:
- passport-local: local username and password authentication
- passport-facebook: authenticate with Facebook via OAuth
- passport-twitter: authenticate with Twitter via OAuth
- passport-jwt: use JSON web tokens instead of sessions
There are hundreds of strategies. You can even find modules tailored to specific technologies and databases. For example, in this project, we will use local authentication with MongoDB. To concentrate on the authentication code, we’ll use the MongoDB wrapper Mongoose and the passport-local-mongoose module.
MongoDB
MongoDB is a NoSQL database that uses JSON-formatted documents to store data. Some NodeJS developers prefer MongoDB because of familiarity of JSON, which can be easily manipulated into JavaScript objects. Here’s an example of MongoDB data:
{ name: 'Lori Fields', address: { street: 123 Palm Trace city: Miami, FL zip code: 33101 }},{ name: 'Harry Humbug', address: { street: 6 SW 1st Street city: Deerfield Beach, FL zip code: 33442 }}Authentication application with Passport and ExpressJS
Now that you’ve had a brief overview of Passport and MongoDB, we are ready to begin the project. Here’s the application’s file structure:
.└── login ├── package.json ├── server.js ├── static │ ├── index.html │ ├── login.html │ └── secret-page.html └── user.jsAs you can see, our primary project folder is named login. Inside login we have:
- A folder named static that contains HTML files
- server.js which is the root to our application and contains all our ExpressJS server code, including our routes
- user.js which uses Mongoose to connect to the database and create our user model
- package.json, the configuration file
The code in this tutorial builds on code in 2 previous tutorials:
If you do not understand ExpressJS or express-session, please view the previous tutorials.
Download MongoDB and create a database
Navigate to Install MongoDB Community Edition and click the link for your operating system (Linux, macOS, or Windows). Follow the directions to install and start MongoDB.
Once MongoDB is installed and started, go to the MongoDB command shell.
mongoThen go to the database “users” (and create it, if it doesn’t already exist):
> use usersAt any time, you can exit the MongoDB command shell by typing the quit command.
> quit ()Create a _package.json_ file
Assuming you have already have NodeJS installed, create a package.json file inside the main project folder.
npm init -yInstall ExpressJS and dependencies
Before we start writing code, we must install the necessary dependencies.
Let’s start by installing ExpressJS (server framework), body-parser (parses incoming request bodies), and express-session (cookie-based session middleware).
npm install express body-parser express-sessionNext, we install Passport and passport-local. Passport is the authentication library and passport-local is our core authentication strategy.
npm install passport passport-localNow we install connect-ensure-login, authorization middleware that makes it easy to restrict access to pages. It is built to work hand-in-hand with Passport, and with one function call, we can authorize routes to only logged-in users.
npm install connect-ensure-loginNext, we install Mongoose, an object data mapper (ODM) used to integrate MongoDB with NodeJS. The library simplifies MongoDB data modeling, facilitating the creation of JavaScript objects and database document persistence. The asynchronous nature of NodeJS query functions can make data modeling cumbersome. Using Mongoose in this project will enable us to concentrate on the authentication code instead of document creation and database integration.
npm install mongooseFinally, we install passport-local-mongoose. This strategy integrates Mongoose with the passport-local strategy.
npm install passport-local-mongooseCreate HTML files
Let’s make sure we have all our HTML files properly written and saved in the static directory.
Example index.html:
<!DOCTYPE html><html lang="en"> <head> <title>Welcome Home</title> </head> <body> <a href="/login">Please Login Here!</a> </body></html>