Skip to content

Custom Credential Schemes

A custom credential scheme reads a credential Bearer, API-key, and session schemes do not cover, such as HTTP Basic. You declare where the credential travels and how it appears in OpenAPI; your code extracts and verifies it, and Routa selects, challenges, types, and documents it like any other scheme.

  • authentication configured in src/routa.ts, as in Configuration.
  • A way to verify the credential, such as a password hash lookup. Routa verifies nothing itself.
  1. Write an extractor that turns the credentials after Basic into a user and password, or reports them malformed. It receives that one string and nothing else, and it must not throw: a throw answers 500.

    src/basic.ts
    import type { CustomExtraction } from "@routa-ts/core";
    export function decodeBasic(
    value: string,
    ): CustomExtraction<{ user: string; password: string }> {
    let decoded: string;
    try {
    const bytes = Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
    decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
    } catch {
    return { type: "malformed" };
    }
    const index = decoded.indexOf(":");
    // RFC 7617 allows no control characters in the user ID or password.
    return index === -1 || /[\u0000-\u001f\u007f]/.test(decoded)
    ? { type: "malformed" }
    : {
    type: "credential",
    credential: { user: decoded.slice(0, index), password: decoded.slice(index + 1) },
    };
    }
  2. Declare the scheme with custom. The transport reads the Basic credentials of the Authorization header, the challenge names Basic, and the OpenAPI metadata describes HTTP Basic. authenticate receives the credential extract returns, typed.

    src/routa.ts
    import { createRouta, custom } from "@routa-ts/core";
    import { z } from "zod";
    import { decodeBasic } from "./basic.js";
    import { verifyPassword } from "./passwords.js";
    export default createRouta({
    authentication: {
    principal: z.object({ type: z.literal("user"), id: z.string() }),
    schemes: {
    basicUser: custom({
    transport: { header: "authorization", scheme: "Basic" },
    challenge: { scheme: "Basic", realm: "api" },
    openapi: { type: "http", scheme: "basic" },
    extract: (value) => decodeBasic(value),
    authenticate: async ({ user, password }) => {
    const account = await verifyPassword(user, password);
    return account
    ? { type: "authenticated", principal: { type: "user", id: account.id } }
    : { type: "rejected" };
    },
    }),
    },
    },
    });

    verifyPassword stands for your own code, such as a constant-time comparison against a stored password hash. An empty user ID, as in :password, is valid Basic syntax (RFC 7617), so decodeBasic passes it to verifyPassword. Whether it can authenticate is your verifier’s decision: return no account for it unless your user store really has an empty user ID. A control character in either field is not valid Basic syntax, so decodeBasic reports it malformed.

  3. Protect a route with the scheme.

    src/routes/account/route.ts
    import { createRoute, createRouteRoot, requireAuth } from "@routa-ts/core";
    import { z } from "zod";
    export default createRouteRoot("/account")({
    get: createRoute({
    middleware: [requireAuth({ schemes: ["basicUser"] })],
    responses: { ok: { status: 200, schema: z.object({ id: z.string() }) } },
    run: ({ ctx }) => ({ type: "ok", data: { id: ctx.auth.principal.id } }),
    }),
    });
  4. Check the contract and start the server.

    Terminal window
    npx routa check
    Routa validation passed for 1 route file(s).
    Running TypeScript check: tsc -p tsconfig.json --noEmit
    TypeScript check passed.
    Routa check passed.
    Terminal window
    npm run dev

A request without credentials receives the challenge, and a valid one authenticates. Replace the placeholder user ada with a user your verifyPassword accepts. With -u ada and no password, curl prompts for it, so the password stays out of your shell history. The response carries the ID verifyPassword returns, shown here as the placeholder user_ada:

Terminal window
curl -i http://127.0.0.1:3000/account
curl -i -u ada http://127.0.0.1:3000/account
HTTP/1.1 401 Unauthorized
content-type: application/json; charset=utf-8
www-authenticate: Basic realm="api"
{"type":"https://routa-ts.dev/problems/authentication-required","title":"Authentication required","status":401}
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
{"id":"user_ada"}

Wrong credentials and credentials that are not valid Basic both answer 401 authenticationFailed with WWW-Authenticate: Basic realm="api". The generated OpenAPI declares the scheme from your metadata:

"securitySchemes": { "basicUser": { "type": "http", "scheme": "basic" } }

When a reverse proxy terminates TLS and verifies client certificates, it can forward the verified certificate to Routa in a header. This recipe is complete, provided two things hold: the proxy overwrites or strips any copy of the header a client sends, and only the proxy can reach the application. Otherwise any client can claim any certificate.

nginx.conf
ssl_verify_client on;
ssl_client_certificate /etc/nginx/client-ca.pem;
location / {
# Overwrites any client-supplied copy; nginx omits the header when there is no certificate.
proxy_set_header X-Client-Cert $ssl_client_escaped_cert;
proxy_pass http://127.0.0.1:3000;
}
src/routa.ts
import { X509Certificate } from "node:crypto";
import { createRouta, custom } from "@routa-ts/core";
import { z } from "zod";
import { findServiceByFingerprint } from "./services.js";
export default createRouta({
authentication: {
principal: z.object({ type: z.literal("service"), id: z.string() }),
schemes: {
clientCert: custom({
transport: { header: "x-client-cert" },
openapi: {
type: "mutualTLS",
description: "A client certificate the TLS proxy verified.",
},
extract: (value) => {
try {
return { type: "credential", credential: new X509Certificate(decodeURIComponent(value)) };
} catch {
return { type: "malformed" };
}
},
authenticate: async (certificate) => {
const service = await findServiceByFingerprint(certificate.fingerprint256);
return service
? { type: "authenticated", principal: { type: "service", id: service.id } }
: { type: "rejected" };
},
}),
},
},
});

OpenAPI mutualTLS tells clients to present a certificate during the TLS handshake, which is what they do: the proxy, not Routa, performs it. Without a challenge override, a 401 challenges clientCert, the scheme name.

DPoP sends an access token as Authorization: DPoP <token> and a proof of key possession in a separate DPoP header. A custom scheme handles the access token. It cannot verify the proof: a custom scheme reads one transport, so extract never sees the DPoP header. This recipe is partial.

src/routa.ts
import { createRouta, custom } from "@routa-ts/core";
import { z } from "zod";
import { verifyAccessToken } from "./tokens.js";
/** RFC 9449 `ath`: the base64url SHA-256 hash of the access token. */
async function accessTokenHash(token: string) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token));
return Buffer.from(digest).toString("base64url");
}
export default createRouta({
authentication: {
principal: z.object({
type: z.literal("user"),
id: z.string(),
jkt: z.string(),
ath: z.string(),
}),
schemes: {
dpopToken: custom({
transport: { header: "authorization", scheme: "DPoP" },
challenge: { scheme: "DPoP" },
openapi: { type: "http", scheme: "dpop" },
authenticate: async (token) => {
const claims = await verifyAccessToken(token);
if (!claims?.cnf?.jkt) {
return { type: "rejected" };
}
// Keep the key thumbprint the token is bound to and the token's hash, so the
// proof check can compare both.
return {
type: "authenticated",
principal: {
type: "user",
id: claims.sub,
jkt: claims.cnf.jkt,
ath: await accessTokenHash(token),
},
};
},
}),
},
},
});

Verify the proof in route middleware that runs after requireAuth: declare the dpop header as middleware input, check its signature, htm, htu, iat, and jti, compare its key thumbprint with ctx.auth.principal.jkt, compare its ath claim with ctx.auth.principal.ath, and return your own reject outcome when any check fails. The ath check is required (RFC 9449 §4.3): without it, a proof made with the same key for a different access token passes. Until that middleware runs, the token alone authenticates the request, so put it on every operation that accepts the scheme.

HTTP message signatures sign request components and send the result in Signature and Signature-Input headers. A custom scheme can read one of them, such as { header: "signature-input" } to find the key ID, but extract cannot see the other header or the signed components. This recipe is partial: authenticate the key ID in the scheme, then verify the signature in route middleware after requireAuth, with every signed header declared as middleware input. Signatures over components middleware cannot read, such as the raw body, cannot be verified in this release.

A custom scheme describes how a credential travels on one HTTP request: which header, Authorization auth-scheme, or cookie carries it. Many security standards are protocols around a credential rather than a place to carry one. Each fits Routa differently:

Standard What it is How it fits
OAuth 2.0 A protocol for obtaining an access token Run the flow in your routes or provider; authenticate the token with bearer
OpenID Connect An OAuth 2.0 sign-in protocol Issue a session or token after sign-in; authenticate it with sessionCookie or bearer
WebAuthn and passkeys A browser ceremony that proves a user holds a key Your application or provider runs it, then issues a session you read with sessionCookie
HTTP Basic A credential in Authorization: Basic A complete custom recipe, above
Mutual TLS Certificate authentication during the TLS handshake Happens in your proxy or platform; the proxy-forwarded certificate is a complete custom recipe, above
DPoP A token plus a proof in a second header Partial: a custom scheme reads the token; route middleware verifies the proof
HTTP message signatures A signature over several request components Partial: a custom scheme reads one header; route middleware verifies the signature

Routa has no built-in support for any provider or protocol flow, and it never runs a sign-in ceremony itself.

Problem Fix
ROUTA_AUTH_TRANSPORT_OVERLAP Another scheme already reads the header, auth-scheme, or cookie. Give each scheme its own transport, and accept every credential format in one authenticator
ROUTA_AUTH_CONFIG_INVALID naming openapi Make the metadata describe the transport: http for an Authorization auth-scheme, apiKey for a header or cookie, mutualTLS for a certificate header
Authorization: Basic … answers 401 with every challenge No scheme reads the Basic auth-scheme. Check the transport’s scheme, and that the route accepts the scheme
A value with a comma answers 401 without calling extract Routa treats a header value with a comma as a repeated header. Send the credential in a form without commas, such as percent-encoded
A request answers 500 and the log says the extraction threw Return { type: "malformed" } from extract for values it cannot read instead of throwing