The Wayback Machine - https://web.archive.org/web/20240529084537/https://www.geeksforgeeks.org/basic-authentication-in-node-js-using-http-header/
Open In App

Basic Authentication in Node.js using HTTP Header

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 module
const express = require("express");
const fs = require("fs");
const path = require('path');
 
const app = express();
 
function authentication(req, res, next) {
    const authheader = req.headers.authorization;
    console.log(req.headers);
 
    if (!authheader) {
        let err = new Error('You are not authenticated!');
        res.setHeader('WWW-Authenticate', 'Basic');
        err.status = 401;
        return next(err)
    }
 
    const auth = new Buffer.from(authheader.split(' ')[1],
        'base64').toString().split(':');
    const user = auth[0];
    const pass = auth[1];
 
    if (user == 'admin' && pass == 'password') {
 
        // If Authorized user
        next();
    } else {
        let 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 client
app.use(authentication)
app.use(express.static(path.join(__dirname, 'public')));
 
// Server setup
app.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: 



Similar Reads

How to make a request using HTTP basic authentication with PHP curl?
Making secure API requests is a common requirement in web development, and PHP provides a powerful tool for this purpose, which is cURL. The challenge is to seamlessly integrate HTTP basic authentication with PHP cURL for secure API communication. This involves not only transmitting sensitive user credentials securely but also ensuring that the PHP
3 min read
Why are HTTP cookies used by Node.js for sending and receiving HTTP cookies?
The HTTP protocol is one of the most important protocols of the Application layer of the OSI model. The main use of this protocol is for sending hypertext information to the client to the server and server to the client to communicate on the World Wide Web. But, the HTTP protocol is a stateless protocol which means that this protocol cannot maintai
5 min read
Will the 'error' event ever be emitted on 'http.IncomingMessage' in a node.js http.request ?
In this article, we will see how to handle the 'error' event that is emitted on 'http.IncomingMessage' in a node.js http.request. In Node.js, the 'http.IncomingMessage' object is used to represent the incoming HTTP request message. This object is a readable stream, and it can emit various events such as 'data', 'end', and 'error'. One of the events
3 min read
How to Click on header to add another header in jQuery ?
In this article, we will see how to add a new header element after clicking the existing header elements in jQuery. To add the new header element, the delegate() method is used. Syntax: $(selector).delegate("Selected_elements", function() { $(this).after("content"); }) Here, we use delegate() method to add one or more event handlers to the specifie
1 min read
How to define whether a header cell is a header for a column, row, or group of columns or rows in HTML 5?
In this article, we will learn how to specify whether a header cell is a header of a column, row, or group of columns or rows. The <th> tag is used to specify the heading for an <table> element, typically for the columns of the table. However, in specific cases, the header can be used to define the heading of a row or a group of columns
2 min read
Explain HTTP authentication
We are in big doors to the digital era where comfort is the main driver. Enjoying all the convenience right from ordering merchandise and paying bills to get services while sitting on the couch. This is how we developed the internet to work for us. Here, authentication comes in and every web resource wants to know who you are because your details a
5 min read
HTTP header X-Forwarded-Host
The HTTP X-Forwarded-Host header is a request-type header de-facto standard header. This header is used to identify the original request made by the client. Because the hostnames and the ports differ in the reverse proxies that time this header took the leader and identify the original request. This header can also be used for debugging, creating l
1 min read
How to parse HTTP Cookie header and return an object of all cookie name-value pairs in JavaScript ?
To parse HTTP Cookie header we will spilt the cookies data and create objects from the key-value extracted from cookies. Cookies are simply small text files that a web server sends to the user's browser. They contain the following data. Name-value pair with actual data.The expiry date for when the cookie becomes invalid.Domain and path of the serve
3 min read
How to make Basic Header markup using jQuery Mobile ?
jQuery Mobile is a web-based technology used to make responsive content that can be accessed on all smartphones, tablets, and desktops. In this article, we will be making Basic Header markup using jQuery Mobile. Approach: First, add jQuery Mobile scripts needed for your project. <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jq
1 min read
Difference between HTTP/2 and HTTP/1.1
HTTP stands for hypertext transfer protocol & it is used in client-server communication. By using HTTP user sends the request to the server & the server sends the response to the user. There are several stages of development of HTTP but we will focus mainly on HTTP/1.1 which was created in 1997 & the new one is HTTP/2 which was created
3 min read