Sitemap

NodeJs Series (Part#4) — Basic Authentication with “basic-auth” Module.

1 min readDec 9, 2024

--

This article continues from the previous article, where we manually checked the username and password in the Authorization header. To simplify the process, we are now using the basic-auth module.

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

The basic-auth module in Node.js makes it easier to handle Basic Authentication by parsing the Authorization header and extracting the credentials

Step 1: Install the basic-auth Module

npm install basic-auth

Step 2: Implement Basic Authentication Using the basic-auth Module

  1. Open the app.js file
  2. Replace the below basicAuth Middleware in app.js
function basicAuth(req, res, next) {
const credentials = basicAuth(req); // Extract credentials from the Authorization header

if (!credentials) {
return res.status(401).json({ message: 'No credentials provided' });
}

// Set your own username and password
const validUsername = 'user';
const validPassword = 'password';

if (credentials.name === validUsername && credentials.pass === validPassword) {
next(); // Authentication passed, proceed to the route
} else {
return res.status(403).json({ message: 'Forbidden: Invalid credentials' });
}
}

Step 2: Run the Server

node app.js

Step 3: Testing the API

  1. Open Postman.
  2. Select the method as GET and enter the URL http://localhost:3000/api/secure-data.
  3. Under the Authorization tab, select Basic Auth.
  4. Enter the username (user) and password (password).
  5. Send the request, and you should receive a response
{ "message": "This is a protected route, accessible only with valid credentials!" }

Before proceeding further, let’s first understand what middleware is and how it works in the Next Article.

--

--

Zeeshan Ali
Zeeshan Ali

Written by Zeeshan Ali

I am a Software Architect with 12 years of experience in Microsoft technologies. I specialize in designing and implementing high-performance, scalable solutions