Skip to content
Related Articles

Related Articles

Improve Article

How to check user authentication in GET method using Node.js ?

  • Last Updated : 22 Apr, 2021

There are so many authentication methods like web token authentication, cookies based authentication, and many more. In this article, we will discuss one of the simplest authentication methods using express.js during handling clients get a request in node.js with the help of the HTTP headers. 

Approach: HTTP protocols used various types of headers for authentication the client we will use the WWW-Authenticate header. 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:

When the request header of the client does not contain WWW-Authenticate header servers response header set
the header is res.setHeader(“WWW-Authenticate”, ‘Basic’) and set status code 401 and after this, a pop will
appear on the client-side for valid authentication.



Authentication Form:

Module Installation: Install the express module using the following command.

npm install express

Project structure:

index.js




// Importing required modules
const { response } = require("express");
const express = require("express");
const app=express()
  
// Handling get request from the client side
app.get("/",(req,res,next)=>{
  
     // Checking the header of the authorization
    var authheader=req.headers.authorization;
    console.log(authheader)
    if(!authheader){
        
        var err=new Error("You are not authenticated")
        // Set the header for the response
        res.setHeader("WWW-Authenticate",'Basic')
        err.status=401
        return next(err)
    
    }
    console.log(authheader)
  
    // Decrypt the user name and the password
    var auth = new Buffer.from(authheader.split(' ')[1],
    'base64').toString().split(':');
    var user = auth[0];
    var pass = auth[1];
  
    // Checking the details
    if (user == 'admin' && pass == 'password') {
      res.send("Welcome you are authorized")
    } else {
        var err = new Error('You are not authenticated!');
        res.setHeader('WWW-Authenticate', 'Basic');
        err.status = 401;
        return next(err);
    }
  
})
app.listen(3000,()=>{
  console.log("Server is starting")
})

Run index.js using the following command:

node index.js

Output:

  • 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: 




My Personal Notes arrow_drop_up
Recommended Articles
Page :