Passport.js & Node : Authentication Tutorial for Beginners - RisingStack Engineering (2024)

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:

  1. Getting started with Node.js
  2. Using NPM
  3. Understanding async programming
  4. Your first Node.js HTTP server
  5. Node.js database tutorial
  6. Node.js request module tutorial
  7. Node.js project structure tutorial
  8. Node.js authentication using Passport.js[ this article ]
  9. Node.js unit testing tutorial
  10. Debugging Node.js applications
  11. Node.js Security Tutorial
  12. How to Deploy Node.js Applications
  13. 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.js & Node : Authentication Tutorial for Beginners - RisingStack Engineering (2)

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:

  1. User enters username and password
  2. The application checks if they are matching
  3. If they are matching, it sends aSet-Cookieheader that will be used to authenticate further pages
  4. When the user visits pages from the same domain, the previously set cookie will be added to all the requests
  5. 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-sessionmodule, 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-localmodule 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, thefindUserwould 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 thefindUserreturns 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.

Passport.js & Node : Authentication Tutorial for Beginners - RisingStack Engineering (2024)
Top Articles
Project Management: Using Smartsheet With Power Bi Reporting
User Types and Permissions | Smartsheet Learning Center
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Weeminuche Smoke Signal
Plus Portals Stscg
Daniela Antury Telegram
104 Presidential Ct Lafayette La 70503
Pro Groom Prices – The Pet Centre
Lonadine
Nebraska Furniture Tables
Mary Kay Lipstick Conversion Chart PDF Form - FormsPal
iOS 18 Hadir, Tapi Mana Fitur AI Apple?
Quest Beyondtrustcloud.com
Missed Connections Dayton Ohio
Michigan cannot fire coach Sherrone Moore for cause for known NCAA violations in sign-stealing case
Tnt Forum Activeboard
How do I get into solitude sewers Restoring Order? - Gamers Wiki
White Pages Corpus Christi
Craigslist Maui Garage Sale
Transactions (zipForm Edition) | Lone Wolf | Real Estate Forms Software
Boscov's Bus Trips
Craigslist Pearl Ms
Menus - Sea Level Oyster Bar - NBPT
About My Father Showtimes Near Copper Creek 9
UMvC3 OTT: Welcome to 2013!
Sand Dollar Restaurant Anna Maria Island
Kohls Lufkin Tx
1145 Barnett Drive
Dashboard Unt
Rugged Gentleman Barber Shop Martinsburg Wv
Speedstepper
897 W Valley Blvd
Alternatieven - Acteamo - WebCatalog
Amazing Lash Bay Colony
Taktube Irani
Kokomo Mugshots Busted
Hattie Bartons Brownie Recipe
Bay Focus
Die Filmstarts-Kritik zu The Boogeyman
Today's Gas Price At Buc-Ee's
MSD Animal Health Hub: Nobivac® Rabies Q & A
Actor and beloved baritone James Earl Jones dies at 93
The Wait Odotus 2021 Watch Online Free
Rocket Lab hiring Integration & Test Engineer I/II in Long Beach, CA | LinkedIn
Sandra Sancc
Lorton Transfer Station
Server Jobs Near
Benjamin Franklin - Printer, Junto, Experiments on Electricity
Canonnier Beachcomber Golf Resort & Spa (Pointe aux Canonniers): Alle Infos zum Hotel
Arginina - co to jest, właściwości, zastosowanie oraz przeciwwskazania
Makemkv Key April 2023
Escape From Tarkov Supply Plans Therapist Quest Guide
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 5687

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.