Multi-Factor Authentication (MFA) with Redis Cache and OTP

Want to implement Multi-Factor Authentication (MFA)? Follow this tutorial to implement MFA using Redis Cache and OTP in your applications.
guest-post,multi-factor-authentication-using-redis-cache-and-otp
Table of Contents

Goal

Securing your web applications from unauthorized users is very important. You can increase the security with One Time Password (OTP) authentication in addition to the login credentials. An OTP is sent to the user’s email when they want to log in. This is a form of multi-factor authentication (MFA).

It is essential to learn how to apply Multi-Factor authentication in real-world applications, and this tutorial got you covered. This tutorial explains how to store users’ sessions in the Redis Store and send OTP using Nodemailer for authentication.

Goal

This tutorial helps you understand:

  • What is Redis?
  • How to utilize the Redis Store?
  • How to set up an SMTP service using Nodemailer?
  • How to protect routes?

Prerequisites

To follow this tutorial, make sure you have:

As everything is in place, let’s jump right in.

Set Up the Server

In this section, you will learn how to start an Express server.

  1. Create a new folder and open it in a text editor. In this tutorial, this folder is named , but you can decide to call it anything you want.

  2. Open the terminal in the project’s path and run the following code to install the dependencies needed to start the Express server.

    The Express dependency will be used to set up the backend server and nodemon, installed as a devDependency, which will watch the file system and restart the server when a change is made.

    Express and Nodemon Installation

  3. Create a new file named in the project’s directory. For simplicity, this file will contain all the server code for this application.

  4. Add the following codes in the file to set up an Express server to listen on port .

  5. Open and add the following code to start the server.

  6. Start the server in development mode by running in your terminal.

    Express server

Set Up Nodemailer

Nodemailer is a Node.js module that allows you to send emails using an email service or an SMTP server.

To set up Nodemailer, you need to provide your email or SMTP service credentials.

Google mailing service (Gmail) will not support the use of third-party apps or devices like Nodemailer starting from May 30, 2022.

For this tutorial, we will use Microsoft’s Outlook Maling Service to send emails.

Set Up Outlook

  1. Navigate to Outlook’s sign-up page to register for an Outlook account if you don’t have one.

  2. Add your phone number if you are prompted to do so.

    This step can be skipped.

Sending Emails

After setting up your Outlook account, the next step is to use your Outlook account’s credential to send emails through Nodemailer.

  1. Open your terminal and install the dependency.

    This module only needs your Outlook account credentials and message to send emails.

    Now, run the code below in your terminal to install the dependency:

  2. Import the module into and add the configurations needed to send emails:

  3. To test the application, use an API testing application like Postman and make a POST request to , passing and to the body of the request.

    Postman

Generate OTPs

In the previous section, you've successfully configured Nodemailer and used it to send emails. This section will show you how to generate a random number and how to add this random number to the message sent to the user.

You can generate this random number using:

  1. A NodeJS module like UUID, shortid, nanoid, etc.

This tutorial uses the module to generate random numbers.

  1. In the terminal, install the module. This module will create a random set of characters as the OTP. Run the following command in your terminal:

  2. After installing the module, import it into and use it to generate six random digits.

  3. Add the OTP to the message sent to the user’s email.

  4. Make a POST request to , passing only the email address.

    Email test

  5. Check the email address for which the OTP is sent.

    Gmail

Redis

Now that the OTP part of the authentication is settled, let’s set up the next part of the authentication. This section covers what Redis is and how to use the Redis Store to cache data.

What is Redis?

Redis, also known as Remote Dictionary Server, is an open-source (BSD licensed), in-memory data structure store. Developers use it as a database, cache, and message broker. It is a fast, lightweight database that structures data in key-value pairs.

Redis Cache

Storing and retrieving cached data from Redis is faster than traditional databases as it retrieves and stores data in the main memory (the RAM). The data can be users’ sessions or responses to requests.

The only downside is that data can be lost if the computer crashes.

Setting up Redis

Setting up Redis locally for Linux and Mac computers is simply straightforward.

Follow the official documentation for Linux and macOS

For Windows, you need to install Windows Subsystem for Linux Version 2 (WSL 2) and a Linux Distro on your local machine.

This tutorial uses Redis Cloud to set up the Redis database. Redis Cloud starts with Free a subscription fee that grants 30MB of storage. This is perfect for this simple application.

  1. Create a new Redis Cloud account if you don’t have one.

    Redis Cloud Set Up

  2. Click on Let’s start free and let Redis create a cloud database.

  3. Click on Configurations and copy your Public endpoint. This endpoint will be used to set up the Redis application.

    Public endpoint

  4. Still on the Configurations tab, copy your Default user password.

    Password

  5. Run in your terminal. Import the dependency into , and set up the using the Redis cloud endpoint.

  6. Start up the server in your terminal and view the result.

    Redis Test

Sessions

Now that Redis has been added to the application, let’s set up users’ sessions using Express Sessions.

Set Up Express Sessions

  1. Install the and modules in your terminal.

    The module allows you to create a session in the client’s browser. And the module enables you to set Redis as the session store. Run the following command in your terminal.

  2. Import and into and configure the session store.

Storing OTPs

Attributes stored in a session without a database are removed after the server refreshes. With the help of Redis cache, attributes in a session can be retrieved fast and saved even when the server restarts.

The user’s OTP should be saved in the session before sending it to the user’s email.

Open your file and add the code as follows.

The following code stores the OTP in the session, redirects when the email has been sent, and verifies the OTP provided with the one stored in the session.

Protecting Routes

Preventing unauthorized/unauthenticated users from accessing a specific route or a piece of important information is essential in various applications. In this section, you'll learn how to create a middleware that will authenticate the users accessing a specific route.

In this tutorial, the protected route is

  1. Create a route to in and add the middleware

  2. Create the middleware function and verify if the user is authenticated.

Logout

The logout route will also be protected using the middleware to prevent requests from users who are not signed in.

Set Up the Frontend

It’s time to put the backend code into actual functionality. This tutorial makes use of Embedded JavaScript Template (EJS) as the frontend of this application.

Setting up EJS

  1. Install the EJS Module

  2. Once the installation is complete, open your and use as the default view engine

  3. In this application, there are only three routes. The login, verify, and home routes. You need to render an file when accessing the routes.

    Modify the routes using the code as follows:

  4. Create a folder named , and inside, create the various files.

    When the server is rendering an ejs file, it checks in the views folder for the file. So, this name is not optional.

    Folder Structure

Style these various routes as you like

Login Route

Add the following code to to set up the Login route.

Verify Route

Open and set up the verify page as follows.

Home Route

This is the route that is protected. The page can contain sensitive information that must not be accessible to unauthenticated users.

Open and configure the home route as follows.

Conclusion

This tutorial taught you how to set up Nodemailer, Redis Cloud, and Multi-Factor Authentication. With these, you've learned to secure your applications from unauthenticated users.

Do you think you can use this to build complex and scalable applications?

MFA with LoginRadius

You can also set up MFA with LoginRadius instead of setting up everything manually with Redis. You can sign up for a free account here.

Refer to this developer-friendly documentation to get started with your MFA setupdocs/guide/mfa/) for your web and mobile apps.

Resources

Click here to access the sample code used in this tutorial on GitHub

Fredrick Emmanuel
By Fredrick EmmanuelHe is a full-stack developer who has written and developed a few personal projects with MERN/PERN stack and built APIs. He generally uses Node.js-based tech stacks to solve challenging algorithms, build scalable applications, and aspire to gain more technical know-how.
Featured Posts

How to Implement JWT Authentication for CRUD APIs in Deno

Multi-Factor Authentication (MFA) with Redis Cache and OTP

Introduction to SolidJS

Build a Modern Login/Signup Form with Tailwind CSS and React

Implement HTTP Streaming with Node.js and Fetch API

NestJS: How to Implement Session-Based User Authentication

NestJS User Authentication with LoginRadius API

How to Authenticate Svelte Apps

Flutter Authentication: Implementing User Signup and Login

How to Secure Your LoopBack REST API with JWT Authentication

Node.js User Authentication Guide

Your Ultimate Guide to Next.js Authentication

Local Storage vs. Session Storage vs. Cookies

How to Secure a PHP API Using JWT

Using JWT Flask JWT Authentication- A Quick Guide

Build Your First Smart Contract with Ethereum & Solidity

What are JWT, JWS, JWE, JWK, and JWA?

How to Build an OpenCV Web App with Streamlit

32 React Best Practices That Every Programmer Should Follow

How to Build a Progressive Web App (PWA) with React

Bootstrap 4 vs. Bootstrap 5: What is the Difference?

JWT Authentication — Best Practices and When to Use

What Are Refresh Tokens? When & How to Use Them

How to Upgrade Your Vim Skills

How to Implement Role-Based Authentication with React Apps

How to Authenticate Users: JWT vs. Session

How to Use Azure Key Vault With an Azure Web App in C#

How to Implement Registration and Authentication in Django?

11 Tips for Managing Remote Software Engineering Teams

Implementing User Authentication in a Python Application

Add Authentication to Play Framework With OIDC and LoginRadius

Share On:
Share on TwitterShare on LinkedIn