Koa Basic HTTP Authentication Middleware

4.0.0 · active · verified Wed Apr 22

koa-basic-auth provides a straightforward middleware for implementing blanket HTTP Basic Authentication within Koa applications. It's designed for simple use cases where a single username and password (or just one of them since v4.0.0) protects all subsequent middleware in the stack. The current stable version is 4.0.0. Releases are tied to the Koa ecosystem, typically stable and less frequent, with major updates addressing underlying security practices or JavaScript module changes. Its key differentiator is its simplicity and explicit focus on 'blanket' authentication, contrasting with more complex authentication libraries that offer granular control, roles, or advanced strategies. It is not intended for fine-grained access control but rather for protecting entire sections of an application.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to apply blanket basic authentication to a Koa application, including essential custom 401 error handling and setting the WWW-Authenticate header to prompt clients. Uses environment variable for password for security.

const auth = require('koa-basic-auth');
const Koa = require('koa');
const app = new Koa();

// custom 401 handling to present a Basic Auth challenge to the client
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.set('WWW-Authenticate', 'Basic');
      ctx.body = 'Authentication Required';
    } else {
      throw err;
    }
  }
});

// Apply basic authentication to all downstream middleware
// Use environment variables for sensitive credentials in production
app.use(auth({ name: 'tj', pass: process.env.BASIC_AUTH_PASS ?? 'tobi' }));

// This middleware will only execute if authentication succeeds
app.use(async (ctx) => {
  ctx.body = 'Welcome, authenticated user!';
});

const port = process.env.PORT || 3000;
app.listen(port, function () {
  console.log(`Koa server listening on port ${port}`);
});

// To test with curl: curl -H "Authorization: basic dGo6dG9iaQ==" http://localhost:3000/

view raw JSON →