Basic Authentication in Node.js using HTTP Header

11 Feb, 2021
Authentication of the client is the first step before starting any Application. The basic authentication in the Node.js application can be done with the help express.js framework. Express.js framework is mainly used in Node.js application because of its help in handling and routing different types of requests and responses made by the client using different Middleware. 
HTTP WWW-Authenticate header is a response-type header and it serves as a support for various authentication mechanisms which are important to control access to pages and other resources as well.
Explanation of the Authentication:
Module Installation: Install the express module using the following command.
npm install express
Project structure:
Project Structure
Filename- index.js
Javascript
// Requiring moduleconst express = require("express");const fs = require("fs");var path = require('path'); const app = express(); function authentication(req, res, next) {    var authheader = req.headers.authorization;    console.log(req.headers);     if (!authheader) {        var err = new Error('You are not authenticated!');        res.setHeader('WWW-Authenticate', 'Basic');        err.status = 401;        return next(err)    }     var auth = new Buffer.from(authheader.split(' ')[1],    'base64').toString().split(':');    var user = auth[0];    var pass = auth[1];     if (user == 'admin' && pass == 'password') {         // If Authorized user        next();    } else {        var err = new Error('You are not authenticated!');        res.setHeader('WWW-Authenticate', 'Basic');        err.status = 401;        return next(err);    } } // First step is the authentication of the clientapp.use(authentication)app.use(express.static(path.join(__dirname, 'public'))); // Server setupapp.listen((3000), () => {    console.log("Server is Running ");})
Run index.js using the following command:
node index.js
Open any browser with http://localhost:3000 location in a private window(in order to avoid a saved password and username). A pop will occur near the address bar. Fill in the username and password that are mention in the code.
If the entered username and password match the mention, then location index.html will render on the browser.
Explanation: The first middleware is used for checking the authentication of the client when the server start and the client enter the localhost address. Initially req.headers.authorization is undefined and next() callback function return 401 status code unauthorized access to the browser. The client fills the credentials and the credentials encrypted in base64 format. After that, it decrypts the base64 format data that contains username and password, then after checking the username and password is correct, the next() method calls the next middleware that is mention below the authentication middleware, otherwise the authentication form pop again and again.
Request Header Details: 
mridulmanochagfg
Node.js-Misc
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React