Koa.js Basic HTTP Authentication in Browser With Username and Password Using koa-basic-auth Library Full Project For Beginners

 

Welcome folks today in this blog post we will be implementing basic http authentication in browser with username and password using koa-basic-auth library in koa.js.All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to install the below library using the npm command as shown below

 

 

npm i koa-basic-auth

 

 

After installing this library you can make an app.js file and copy paste the following code

 

 

app.js

 

 

//This is what the authentication would be checked against
var credentials = { name: 'Ayush', pass: 'India' }

var koa = require('koa');
var auth = require('koa-basic-auth');
var _ = require('koa-router')();

var app = koa();

//Error handling middleware
app.use(function *(next){
   try {
      yield next;
   } catch (err) {
      if (401 == err.status) {
         this.status = 401;
         this.set('WWW-Authenticate', 'Basic');
         this.body = 'You have no access here';
      } else {
         throw err;
      }
   }
});

// Set up authentication here as first middleware. 
// This returns an error if user is not authenticated.
_.get('/protected', auth(credentials), function *(){
   this.body = 'You have access to the protected area.';
   yield next;
});

// No authentication middleware present here.
_.get('/unprotected', function*(next){
   this.body = "Anyone can access this area";
   yield next;
});

app.use(_.routes());
app.listen(3000);

Leave a Reply