Readme

honoBasicAuthMiddleware

You should use https://hono.dev/middleware/builtin/basic-auth instead.

Used to authenticate your HTTP vals build with Hono behind a username/password challenge. Browsers store this information alongside your other passwords.

Screenshot 2024-05-25 at 7.30.11 AM.png

Usage

In basicAuthButton, I secure two routes (one for viewing a value, one for updating it) behind a username/password combo stores in my Env variables.

/** @jsxImportSource npm:hono@3/jsx */ import { honoBasicAuthMiddleware } from "https://esm.town/v/jdan/honoBasicAuthMiddleware"; import { blob } from "https://esm.town/v/std/blob?v=12"; import { Hono } from "npm:hono"; /** Authenticate the URL */ const secretUsername = Deno.env.get("BUTTON_USERNAME"); const secretPassword = Deno.env.get("BUTTON_PASSWORD"); app.use(honoBasicAuthMiddleware(secretUsername, secretPassword)); app.get("/", async (c) => { const lastPressed = await blob.getJSON(blobStorageKey) || "Never"; return c.html( <div> <h1>Last Pressed: {lastPressed}</h1> <form method="POST" action="/press"> <input type="submit" /> </form> </div>, ); });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { Buffer } from "node:buffer";
import { createMiddleware } from "npm:hono/factory";
export function honoBasicAuthMiddleware(secretUsername: string, secretPassword: string) {
return createMiddleware(async (c, next) => {
const authHeader = c.req.header("authorization");
if (!authHeader) {
return promptForAuth(c);
}
const auth = authHeader.split(" ");
if (auth[0] !== "Basic") {
return promptForAuth(c);
}
const base64Credentials = auth[1];
const credentials = Buffer.from(base64Credentials, "base64").toString("ascii");
const [username, password] = credentials.split(":");
if (username !== secretUsername || password !== secretPassword) {
return promptForAuth(c);
}
await next();
});
}
/**
* WWW-Authenticate will prompt the user for credentials
* and save those credentials to storage for subsequent requests
*/
function promptForAuth(c) {
c.header("WWW-Authenticate", "Basic realm=\"Secure Area\"");
return c.text("Unauthorized", 401);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
2
stevekrouse avatar
jdan avatar

LOL no, not at all. Thanks, will use that instead.

v5
May 25, 2024