Basic access authentication is a method for enforcing access controls to resources on the World Wide Web. For
authorization 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, to add confidentiality a secure transportation protocol like TLS(HTTPS) is required.
Cloudflare workers implement the Service Worker API, therefore 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 from the preceding snippet can be generated as follows.
printf "Basic %s\n" $(printf "%s" "username:password" | base64)
# Basic dXNlcm5hbWU6cGFzc3dvcmQ=