TezXTezX
Middleware

basicAuth

The basicAuth middleware enforces HTTP Basic Authentication on incoming requests. It verifies the Authorization, Basic... header, checks credentials, and blocks unauthorized clients.

When to Use

  • Protect admin routes (such as /admin, /dashboard)
  • Secure APIs during development or testing without OAuth/JWT
  • Add a quick access gate to staging servers

Import

import { basicAuth } from "tezx/middleware";

Options

export type BasicAuthOptions = {
  /**
   * Function to validate credentials.
   */
  validate: (
    username: string,
    password: string,
    ctx: Context
  ) => boolean | Promise<boolean>;

  /**
   * Authentication realm (shown in browser login popup).
   * @default "Restricted Area"
   */
  realm?: string;

  /**
   * Custom handler when authentication fails.
   * Must return an HttpBaseResponse.
   */
  onUnauthorized?: (ctx: Context, error?: Error) => HttpBaseResponse;
};

Usage Examples

1. Static Credentials

import { basicAuth } from "tezx/middleware";

const auth = basicAuth({
  validate: (username, password) =>
    username === "admin" && password === "secret",
});
app.use("/admin", auth, (ctx) => {
  ctx.json({ message: "Welcome, admin!" });
});

2. Async Validation (Database)

const auth = basicAuth({
  validate: async (username, password, ctx) => {
    const user = await db.users.findOne({ username });
    return user && user.passwordHash === hash(password);
  },
});

3. Custom Unauthorized Handler

const auth = basicAuth({
  validate: (u, p) => u === "demo" && p === "demo",
  onUnauthorized: (ctx, error) => {
    return ctx.status(401).json({ error: "Access denied", reason: error?.message });
  },
});

How It Works

  1. Reads the Authorization header
  2. Checks that it begins with Basic
  3. Decodes Base64 credentials (username:password)
  4. Calls your validate(username, password, ctx)
    • If valid: attaches ctx.user = { username } and continues
    • If invalid: calls onUnauthorized and stops the request

Accessing the Authenticated User

app.get("/profile", auth, (ctx) => {
  const user = (ctx as any).user;
  return ctx.json({ message: `Hello ${user.username}` });
});

Notes

  • Credentials are sent with every request and only Base64-encoded, so use HTTPS.
  • For production-grade security, consider JWT, OAuth2, or session-based auth.
  • The realm value appears in the browser login popup.