Hono SDK (@auth-platform/hono)#

@auth-platform/hono は Server SDK (@auth-platform/server) の BFF セッション機能を Hono に接続する middleware と route mount helper を提供する。ログイン、callback、logout ルートと、セッション・Bearer access token の認証を Hono context から扱える。

インストール#

pnpm add @auth-platform/server @auth-platform/hono hono

hono は peer dependency である。createServerAuth() の設定、cookie、CSRF、Result/error の扱いは Server SDK (@auth-platform/server) を参照する。

ログイン route と必須セッション#

mountAuthRoutes(app, auth, options?) は ServerAuth handler を次の Hono route に接続し、同じ app を返す。

Method Path(既定 basePath: "/auth") Handler
GET, POST /auth/login login を開始する。
GET /auth/callback OIDC callback を処理する。
GET, POST /auth/logout logout を処理する。

options.basePath の既定値は auth.basePath である。createServerAuth({ basePath }) と異なる path に mount すると、未認証時の redirect 先が mount した path と一致しないため、両方を同じ値にする。

requireSession(auth, options?) は保護 middleware である。認証済みなら authSession、authUser、accessToken を Hono context に設定して後続 handler を実行する。認証されていなければ処理を止め、応答をそのまま返す。未認証時の既定値は onUnauthenticated: "json" で 401 problem JSON、ブラウザー向けには "redirect" を指定して 302 ログイン redirect にできる。一時的な refresh 障害は 503 となり、ログインへ redirect しない。

import { Hono } from "hono";
import { createServerAuth } from "@auth-platform/server";
import { mountAuthRoutes, requireSession } from "@auth-platform/hono";
import type { AuthEnv } from "@auth-platform/hono";

const auth = createServerAuth({
  issuer: process.env.AUTH_ISSUER!,
  clientId: process.env.AUTH_CLIENT_ID!,
  clientSecret: process.env.AUTH_CLIENT_SECRET!,
  redirectUri: process.env.AUTH_REDIRECT_URI!,
  cookieSecret: process.env.AUTH_COOKIE_SECRET!,
});

const app = new Hono<AuthEnv>();
mountAuthRoutes(app, auth);
app.get("/account/profile", requireSession(auth), (c) =>
  c.json({ sub: c.get("authUser").sub, scope: c.get("authSession").scope }),
);

requireSession middleware は refresh/clear が必要な場合に outgoing response へ Set-Cookie を追加する。自分で getSession() を呼び出して Hono response を構築する場合は、戻り値の setCookie または clearCookie を Set-Cookie に追加する。

任意セッション#

authMiddleware(auth) はアクセスを遮断せず、セッションが有効な場合に同じ context 変数を設定する。未認証時は authSession、authUser、accessToken が undefined になる。無効 cookie の消去や refresh cookie の更新が必要なら middleware が response に Set-Cookie を追加する。

import { Hono } from "hono";
import { authMiddleware } from "@auth-platform/hono";
import type { OptionalAuthEnv } from "@auth-platform/hono";

const optionalRoutes = new Hono<OptionalAuthEnv>();
optionalRoutes.get("/welcome", authMiddleware(auth), (c) =>
  c.json({ sub: c.get("authUser")?.sub ?? null }),
);

Bearer access token を保護する API#

bearerTokenMiddleware(options) は Authorization: Bearer <access-token> を issuer JWKS で検証する resource-server middleware である。options は @auth-platform/server の verifier 設定 issuer、任意の audience と fetch に加え、realm(既定値 "api")を受け取る。audience を指定し、API 向けに発行された token だけを受け入れる。

成功時に middleware は次を context に設定する。

  • accessTokenClaims: 検証済み claims と sub / scope
  • accessTokenSubject: subject
  • accessTokenScope: scope 文字列

Bearer header がない場合や不正な場合は 401 と WWW-Authenticate challenge を返す。不正 token は 401、discovery/JWKS 取得など再試行可能な障害は 503 となる。

import { Hono } from "hono";
import { bearerTokenMiddleware } from "@auth-platform/hono";
import type { BearerEnv } from "@auth-platform/hono";

const api = new Hono<BearerEnv>();
api.use(
  "*",
  bearerTokenMiddleware({
    issuer: process.env.AUTH_ISSUER!,
    audience: "https://api.example.com",
    realm: "orders",
  }),
);
api.get("/orders", (c) =>
  c.json({ sub: c.get("accessTokenSubject"), scopes: c.get("accessTokenScope") }),
);

Hono を使わない resource server は createAccessTokenVerifier() を直接利用できる。Next.js App Router で同じ BFF を使う場合は Next.js SDK (@auth-platform/next) を参照する。