Sitemap

NodeJs Series (Part#3) — Basic Authentication.

2 min readDec 9, 2024

--

Press enter or click to view image in full size

In the Previous Article we have created the simple CRDU RESTful Apis using ExpressJS. Lets explore the Basic Authentication in Node.js.

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

Basic Authentication can be implemented by manually checking the credentials in the request headers. Here’s how you can add Basic Authentication to your Node.js app using the Express framework.

Step 1: Create Basic Authentication Middleware

  1. Open the app.js file of your my-app project.
  2. Create a middleware to check the Authorization header for valid credentials. The Authorization header in Basic Authentication contains a base64-encoded string in the format.

Step 2: Set Up the API with Basic Authentication

  • Basic Authentication Middleware:
    The middleware basicAuth extracts the Authorization header from the request. It checks if the header is in the correct format (Basic <base64-encoded-username:password>), decodes the base64 string, and compares the username and password with the expected values. If the credentials are correct, it calls next() to allow the request to proceed to the route handler.
  • Protected Route:
    The route /api/secure-data is protected by Basic Authentication, meaning it can only be accessed if the request contains valid credentials in the Authorization header.

Add the following code in to the app.js file.


function basicAuth(req, res, next) {
const authHeader = req.headers['authorization'];

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

const [scheme, credentials] = authHeader.split(' ');

if (scheme !== 'Basic' || !credentials) {
return res.status(401).json({ message: 'Invalid authorization format' });
}

const decoded = Buffer.from(credentials, 'base64').toString('utf-8');
const [username, password] = decoded.split(':');

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

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

Step 3: Set Up the API with Basic Authentication

Add the following route to the app.js file.

app.get('/api/secure-data', basicAuth, (req, res) => {
res.json({ message: 'This is a protected route, accessible only with valid credentials!' });
});

your code should look like this.

Press enter or click to view image in full size

Step 4: Run the Server

node app.js

Step 5: Testing the API

Using Postman:

  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!" }

--

--

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