close

DEV Community

Muhammad Awais
Muhammad Awais

Posted on

Basic Authentication using NodeJS, Express and MongoDB

Firstly develop this basic method in your app.js of express application to perform basic auth

// Basic Authentication
function auth (req, res, next) {
  console.log(req.headers);
  var authHeader = req.headers.authorization;
  if (!authHeader) {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');
      err.status = 401;
      next(err);
      return;
  }

  var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
  var user = auth[0];
  var pass = auth[1];
  if (user == 'admin' && pass == 'password') {
      next(); // authorized
  } else {
      var err = new Error('You are not authenticated!');
      res.setHeader('WWW-Authenticate', 'Basic');      
      err.status = 401;
      next(err);
  }
}
Enter fullscreen mode Exit fullscreen mode

Secondly call the method before static rendering line of express.static

// first
app.use(auth);
// second
app.use(express.static(path.join(__dirname, 'public')));
Enter fullscreen mode Exit fullscreen mode

In this server will perform basic-auth before giving access or serves up the request coming.

That's it.

Top comments (0)