Skip to Content
hono-bento

Authentication

Pluggable strategies resolve who is calling; an authorizer decides what they may do.

hono-bento doesn't know how your identities work. You provide two small interfaces, and each route declares its requirements.

Strategies

A strategy turns a request into your identity type:

interface AuthStrategy<Identity> {
  name: string;
  authenticate(c: Context): Identity | null | Promise<Identity | null>;
}
  • Return an identity when the request authenticates with this strategy.
  • Return null when the request isn't for this strategy, for example because its header is missing. The next strategy is tried.
  • Throw an HttpError when the credential is present but invalid. The request is rejected at once.
auth.ts
export const apiKeyStrategy: AuthStrategy<Session> = {
  name: 'apiKey',
  async authenticate(c) {
    const key = c.req.header('x-api-key');
    if (!key) return null;
    const match = await findApiKey(key);
    if (!match) throw HttpError.unauthorized('Unknown API key.');
    return { type: 'apiKey', subject: match.id, role: match.role };
  },
};

Authorizer

The authorizer decides whether an identity meets a route's requirements. The framework gives scopes no meaning; your authorizer interprets them as roles, permissions or key capabilities.

interface Authorizer<Identity> {
  authorize(identity: Identity, requirements: AuthRequirements, c: Context): boolean | Promise<boolean>;
}

Return false to send 403 forbidden, or throw an HttpError for a custom error.

Checked at startup

mountSpecs throws at startup, rather than serving a route whose auth can't work as configured, when a route:

  • declares scopes but you didn't pass an authorizer, so nothing would check them and any authenticated caller would get through;
  • requires authentication but no strategies are configured, so it could never be called;
  • names a strategy in auth.strategies that isn't registered, such as a typo;
  • sets allowAnonymous and also requires scopes. An anonymous caller has no identity to check, so it would skip the scopes while signed-in callers without them got a 403. Drop one, and check the identity in the handler if the route behaves differently for signed-in callers.

Route requirements

Routes require authentication by default. Only allowAnonymous: true makes a route public, so forgetting auth can't ship an open endpoint.

auth: { scopes: ['todos.write'] }                  // any strategy, with the scope
auth: { strategies: ['apiKey'], scopes: ['admin'] } // API keys only
auth: {}                                            // anyone authenticated
// no `auth` at all                                 // the same: anyone authenticated
auth: { allowAnonymous: true }                      // public: identity may be null

Prop

Type

The flow

For every route:

  1. Each eligible strategy runs in the order you registered them, until one returns an identity.
  2. If none does, the request gets 401 unauthorized, unless the route has allowAnonymous.
  3. The identity and the strategy's name are stored on the context.
  4. The authorizer checks the requirements. If it returns false, the request gets 403 forbidden.

Resource-level authorization

The authorizer runs before the handler, with the route's requirements and no data. It can say whether a caller may update todos, but not whether they may update this todo: that needs the row.

Check ownership in the query instead. The example keeps one app-level helper that every feature imports, and spreads it into each where:

access.ts
import type { Session } from './auth';

/**
 * Which rows a caller may see and change: spread into a query's `where`, as in
 * `db.todo.update({ where: { id, ...owner } })`. Admins see every row; anyone
 * else, only their own.
 *
 * The authorizer in auth.ts runs before the handler, so it can say whether a
 * caller may update todos, not whether they may update this one. Ownership
 * lives in the query instead: someone else's todo matches no row, so it
 * answers 404 exactly like a todo that doesn't exist, and the API never
 * confirms that another user's id is real.
 */
export interface Owner {
  ownerId?: string;
}

export function ownerScope(session: Session): Owner {
  return session.role === 'admin' ? {} : { ownerId: session.subject };
}
features/todos/store.ts
async update(db: Database, owner: Owner, id: string, input: TodoUpdate): Promise<Todo> {
  return toTodo(await db.todo.update({ where: { id, ...owner }, data: input }));
},

Someone else's todo matches no row, so Prisma throws P2025 and mapPrismaError answers 404, the same as for a todo that doesn't exist. The API never confirms that another user's id is real, and no handler has to remember an ownership check: a store function that takes owner can't be called without one.

Use 403 for what the caller's role can't do at all (the authorizer's job), and 404 for rows they can't see.

OpenAPI

Pass securitySchemes to generateOpenApiDocument, and securityByStrategy to say which scheme each strategy implements. Each route that isn't allowAnonymous then lists only the schemes of the strategies it accepts. See OpenAPI.

On this page