Basic access authentication is a method for enforcing access controls to resources on the World Wide Web. For autorization a client needs to provide an Authorization header with an authentication method Basic and credentials encoded as Base64 i.e. Basic username:password. On unauthorized requests the server should return a response whose header contains a HTTP 401 Unauthorized status and a WWW-Authenticate field with method Basic (see Wikipedia).

Caution. Basic access authentication just encodes the transmitted credentials, in order to add condidentiality a secure transportation prototcol like TLS(HTTPS) is required.

As cloudflare workers implement the Service Worker API it’s straight forward to implement basic access authentication in javascript.

const authorization = "Basic dXNlcm5hbWU6cGFzc3dvcmQ=";

const handle = async function(request) {
  if (request.headers.get("Authorization") !== authorization) {
    return new Response(null, {
      status: "401",
      statusDescription: "Unauthorized",
      body: "Unauthorized",
      headers: {
        "WWW-Authenticate": "Basic"
      }
    });
  }

  return await fetch(request);
}

addEventListener("fetch", function(event) {
  event.respondWith(handle(event.request));
});

The authorization string above was generated as using coreutils.

printf "Basic %s\n" $(printf "%s" "username:password" | base64)
# Basic dXNlcm5hbWU6cGFzc3dvcmQ=