How to configure http auth basic in Node js and Express

How to configure http auth basic in Node js and Express
Reading Time: 2 minutes

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


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Join 22 other subscribers

Leave a Reply

Discover more from javaniceday.com

Subscribe now to keep reading and get access to the full archive.

Continue reading