How to configure http auth basic in Node js and Express


Posted on Aug 04, 2020


featured image
Let’s build a small site in Node.js using Express that will have one protected page img

We are going to use express generator to generate some scaffolding. If you didn’t install it just type this command to install it globally but if you already know all this stuff you might skip this step


npm install express-generator -g

Generate a site with default options:

express auth-basic

The output of that command will show you the generated files:

create : auth-basic/
create : auth-basic/public/
create : auth-basic/public/javascripts/
create : auth-basic/public/images/
create : auth-basic/public/stylesheets/
create : auth-basic/public/stylesheets/style.css
create : auth-basic/routes/
create : auth-basic/routes/index.js
create : auth-basic/routes/users.js
create : auth-basic/views/
create : auth-basic/views/error.jade
create : auth-basic/views/index.jade
create : auth-basic/views/layout.jade
create : auth-basic/app.js
create : auth-basic/package.json
create : auth-basic/bin/
create : auth-basic/bin/www


Go into the folder, build the project with install and run it.

cd auth-basic
npm install
npm start

Open a browser at: http://localhost:3000 to validate everything goes well.

You should see a web page like this:

img

The magic

Now let’s install the module express-basic-auth that will do the magic.

npm install --save express-basic-auth

Modify the module /routes/users.js


var express = require('express');
var router = express.Router();
 
const basicAuth = require("express-basic-auth");
 
const authOptions = {
  challenge: true, //it will cause most browsers to show a popup to enter credentials on unauthorized responses,
  users: {"admin": "admin"},//typically you will get  this info from environment variables or any other source
  authorizeAsync: false,
  unauthorizedResponse: getUnauthorizedResponse,
};
 
/**
 *
 * @param req
 * @returns {string} the text to be displayed when users hit on cancel prompt button
 */
function getUnauthorizedResponse(req) {
  return "Unauthorized";
}
 
/**
 *  GET users listing.
 */
router.get('/', basicAuth(authOptions), function(req, res, next) {
  res.send('Users listing area');
});
 
module.exports = router;


Stop and run again

Navigate to http://localhost:3000/users

You should see a prompt that asks you for credentials. Try click on cancel button and then refresh the page to introduce the credentials you wrote in the code.

Photo by Jon Moore on Unsplash

dev nodejs express security
Search
Side Widget
You can put anything you want inside of these side widgets. They are easy to use, and feature the new Bootstrap 4 card containers!