Koa.js Authentication - Koa.js

What is Koa.js Authentication?

User is granted permission to access, only when the process of authentication is completed. Authentication process facilitates in comparing the credentials with those of the database file of users’ information within the server which is authenticated. Only when the credentials match, the user gets access permission.

How to create Authentication system?

Basic Authentication system is created to make understand the concept using basic HTTP Authentication. Basic HTTP Authentication enables to impose access control and does not require any sessions or cookies. Authorization header should be sent along with every request by the client. The username and password come in a single string as:

Base64 is being encoded with the string. For instance, for username ‘Ayush’ and password ‘India’ the string appears as “Ayush:India” and is sent in the authorization header encoded as:

How to implement Authentication system in Koa.js?

Koa-basic-auth middleware facilitates in implementing the Authentication system in Koa. Koa-basic-auth middleware is installed by:

In app.js file, enter the code:

By the above code, error handling middleware is created to handle all the errors related to authentication. Two routes are created.

  • /protected – route is accessed only with correct authentication header by the user, and for rest error occurs
  • /unprotected – with or without authentication header the route can be accessed by anyone.

A request without an authentication header sent to /protected will result in an error. For instance,

The response appears as:

A request with correct credentials result in expected response. For instance,

The response appears as:

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Koa.js Topics