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);
}