One Login for Every Product: Building a Central Identity Provider on Better Auth
One Login for Every Product: Building a Central Identity Provider on Better Auth
Putting one OpenID Connect issuer on Hono + Better Auth in front of multiple products, with local sessions and the…
·Updated on:··
⚡ Next.js Implementation Guides
In-depth Next.js guides covering App Router, RSC, ISR, and deployment. Get code examples, optimization checklists, and prompts to accelerate development.
By Matija, the developer behind Build with Matija. Between 28 October and 1 November 2026 I put one OpenID Connect issuer in front of my own products and connected the first of them to it. This article is written from that repository's ledger, decision records, audit notes and commits, and from the integration commits in two of the products. Versions: Better Auth and @better-auth/oauth-provider 1.7.14, Hono 4.13, Drizzle 0.45, PostgreSQL 17, Node 24. Last updated 2026-11-02.
If you run more than two products, a central identity provider saves you from rebuilding sign-in in each one and gives you a single place to suspend a person, rotate a key or read an audit trail. I built mine as a small Hono service on Better Auth with its OAuth 2.1 / OIDC provider plugin, and each product signs people in through it with a thin SDK while keeping its own local session and its own permissions. The first product went live on it on 28 October, the day the issuer's first pull requests merged. The more useful part came two days later, when an audit of the issuer before wider rollout found three gaps that every test had passed over: in production all callers shared one rate-limit bucket, tokens could still be issued to users who had just been suspended, and a security header never reached the responses that mattered. This article covers the shape I chose, the decisions behind it, the cost of sharing one SDK across products, and how each of those gaps hid.
Why one identity provider for several products
By late October I had a handful of products on the same stack: a Hono API, a React and Vite front end, PostgreSQL, deployed on my own server. Each one had grown its own sign-in. Every new product meant another copy of password reset, email verification, Google sign-in, two-factor and an admin screen to block someone, and each copy drifted a little from the last.
The repository's mission statement puts the goal in one sentence: "Maintain one authentication codebase with well-versioned integration packages so that new products can adopt sign-in, sessions and API authentication without rebuilding them." Secrets and environment configuration come from the self-hosted Infisical I already run, which I described in Self-Host Infisical: Ultimate VPS Guide for Secrets.
On 1 November that goal became a recorded decision for the whole portfolio: sign-in through BWM Auth across all my apps, including Docket, my work-tracking product. One product still runs elsewhere for now. Recount, my meeting knowledge base, signs people in with WorkOS AuthKit, and its October deploy notes keep AuthKit sign-up switched on.
The shape: one issuer, product-local sessions
The design has three parts.
A central issuer. A Hono service with Better Auth and the OAuth provider plugin: Google sign-in, a consent screen, persisted and encrypted RS256 signing keys, exact issuer discovery, and client registration controlled by an operator. Products are confidential OIDC clients.
Two SDK packages. A Hono package for the product's server and a React package for its front end. They pin the issuer from discovery, require verified ID tokens with state, nonce and PKCE, and bind UserInfo to the verified subject.
Each product keeps its own session and its own permissions. The issuer answers one question: who is this person. The product decides what that person may do inside it.
The third point carries most of the weight, and the merged SDK pull request spells out what it means in practice:
The product stores a mapping from issuer, client and subject to its own local user, and creates its own PostgreSQL session.
Implicit linking by email is off. A central identity whose email matches an existing local account does not take that account over.
Logout in a product is local. Signing out of one product leaves the others alone.
Product sign-up and product access are closed by default and switched on separately.
The tokens the issuer hands back are removed after sign-in, so the product's account table holds no central tokens.
Async, my asynchronous discovery product, records the same rule in its rollout notes: "Central identity does not grant automatic product entitlement. Password login remains fully functional and central logout is decoupled from product sessions."
For anyone who has read Next.js Authentication: 5 Strategies & When to Use Them, this adds a sixth context: authentication shared across products you own. It sits between first-party auth (each app does everything itself) and a hosted identity vendor.
Two products, two integration styles in two days
The first two products connected to the issuer two days apart, and the second one took a simpler route.
Async (28 October) went to production first. The integration added explicit, session-bound account linking behind a runtime flag, then sign-up through BWM Auth. Sign-up uses a server-controlled one-time intent: POST /api/auth/bwm/signup writes a row that lives for five minutes, and the OIDC callback consumes it atomically before it is allowed to create a user. Three switches must all be on (ALLOW_SIGNUP, BWM_SSO_ENABLED, ), and all three default to off. If the central identity's email matches an existing Async user who has not linked it, the callback stops with and sends the person to password sign-in and account connection. The production record lists what was checked with a real Google login: linking in Async, a later BWM login landing on the original local user ID, single sign-on into a second product on another domain, and the local session surviving an Async logout.
Sedule (30 October), my appointment scheduling product, used Better Auth's own social flow for the same job: /sign-in/social, /callback/bwm and , with no intent tables. The safety rules moved into configuration and checks: account linking enabled with implicit linking disabled, a ten-minute freshness requirement on the session that links an identity, central tokens removed from the account table, a unique index on provider and account, and the existing two-factor gate and audit trail extended to the callback. Its tests run against a fake OIDC issuer and cover the cases that matter: a new user created without central tokens, a replayed or forged callback refused, an existing same-email account never merged, an identity owned by another user refused, a stale session refused, and the flag switched off. It ships behind , which is off by default.
The comparison is useful if you are about to do this yourself. If your product already uses Better Auth, the social provider path gives you sign-in, sign-up and linking with very little code of your own, and the protection comes from and a freshness guard. The intent table is worth its extra code when sign-up needs its own server-side gate that you can inspect and expire.
What one shared SDK costs
A shared package makes every product depend on the same versions. The SDK peer-pins Better Auth 1.7.14. Sedule was on 1.7.12, so connecting it meant upgrading Better Auth and all @better-auth/* packages in the product first. Its decision record notes that its auth, two-factor and authentication tests passed unchanged after the upgrade. That went smoothly, and it still means an upgrade of the issuer's dependencies becomes an upgrade across the portfolio.
The packages are not on a public registry. Products vendor a tarball, and the SDK work added reproducible tarballs, a file allow-list, a release guard and a compatibility matrix, with tests that install the packed tarballs from a registry-like scope and rehearse a rollback. The README is direct about the state on 29 October: "Hono/React SDKs remain private alpha tarballs, not stable registry releases."
The CI side has a cost too. The Async rollout record notes that the issuer's CI run after the SDK merge never ran, because GitHub reported a failed payment or a spending limit on the account, so the validation for that merge came from local runs. A shared auth platform needs its own pipeline to stay green, because every product's sign-in waits on it.
Three gaps that every test passed over
On 30 October I had agents build the next set of issuer work in isolated worktrees: client lifecycle, a durable audit trail, cross-product revocation, admin two-factor, SDK distribution, a FastAPI reference client, and finally monitoring and recovery. Each task ended with an evidence document and a decision record waiting for my approval. Three findings from that work are the reason I am writing this article, because each one shows a different way that tests stay green while production is wrong.
1. In production, every caller shared one rate-limit bucket
The issuer's first configuration trusted no proxy headers at all, which is the safe default:
The audit reproduced what that does under NODE_ENV=production against the pinned Better Auth source. With no headers to read and no socket address on the request object, Better Auth's client IP lookup returns null, and it then keys every request to one shared placeholder, no-trusted-ip|<path>. All callers in the world shared one bucket per path, and session rows stored no address. Under test and development the same lookup returns , so every test saw a normal per-client limit.
The fix has two parts. The issuer now resolves the client address itself, with an explicit trusted-proxy model that is off by default. With TRUSTED_PROXY_CIDRS empty, the client is the direct TCP peer and forwarded headers are ignored. With it set, a forwarded header is honoured only when the peer is a trusted proxy, and X-Forwarded-For is read from the right, skipping trusted hops; the first address that is not a trusted proxy is the client. IPv6 addresses are reduced to their /64 for the bucket key, so one host cannot avoid the limit by rotating addresses. The resolved address goes into one header that the server sets and strips from inbound requests, and that header is the only one Better Auth reads:
The custom storage replaces the no-trusted-ip part of Better Auth's key with the identity the server resolved, and stores counters with one atomic upsert in the existing rate_limit table in PostgreSQL. The decision record rejected Redis as new infrastructure for this, and rejected trusting the left-most X-Forwarded-For or a fixed hop count as spoofable or fragile.
One consequence is still open. Behind my current reverse proxy, the proxy is the peer, so until I configure the trusted range all clients again share one bucket. It is now a documented setting with a default I chose, and the metrics and readiness checks make it visible.
If you run Better Auth behind a reverse proxy, check what address your production sessions store. An empty address column is the symptom.
2. Suspended users could still get tokens
The issuer had database hooks meant to stop token creation for users who are not active. The revocation work found that those hooks never run. The OAuth provider plugin creates its token rows directly through the adapter (ctx.context.adapter.create), which skips the hooks. So an authorization code issued before a status change could still be exchanged while the central session survived, and UserInfo was not gated. A second gap sat next to it: a user moved back to pending_approval lost nothing, because only suspended triggered revocation.
The gates now live at the token endpoint and at UserInfo in the issuer's own request handling, and tests pin the behaviour so that they fail if the upstream plugin changes how it stores codes and tokens. That is the general lesson: when a library writes rows through a lower-level path, hooks on the higher-level path give you a check that exists in code and never runs, so put the check at the endpoint you control.
3. A header that never reached the responses that mattered
The issuer set Cache-Control: no-store in a Hono middleware. The monitoring audit found that the header never reached the responses Better Auth returns as-is, because Hono merges headers set before a handler only into responses it builds itself. In a local run, the JWKS and social sign-in endpoints carried no Cache-Control, and discovery carried the upstream value with a 15-second public cache. The same mechanism dropped X-Request-Id, so the request id is now set after the handler. A deployment check that required no-store on discovery had only ever passed in production because the reverse proxy added the header.
All three findings share a cause. In each case the behaviour that mattered happened in a layer the issuer's own code did not control: the production request object, the plugin's adapter call, the raw upstream response. The checks sat one layer above it, in a test environment, a hook or a middleware.
Revocation across products: a bounded delay
Product-local sessions raise an obvious question: if I suspend someone at the issuer, when do the products notice? The answer in BWM Auth is a number.
A product that opts in pulls a signed status assertion from the issuer on a timer. The request is client-authenticated and bound to audience, subject and a nonce, and the answer carries whether the person is active plus a durable "not before" marker. The marker is written in the same transaction as a suspension, a lockout, a global logout or unlinking a person from one product. The measured bounds:
Situation
The decision record compares this with OpenID back-channel logout, which tries once, only deletes sessions, and needs a public logout URL for each client, and with simply keeping product sessions short. A pull on a timer gives a delay I can state in a security review, which matters for the questions in Enterprise Clients: Readiness Checklist for Small Agencies.
The incident playbook lists each lever with its effect: lock out one person everywhere, end all of someone's sessions, remove a person from one product, stop one product from signing anyone in, rotate a product's secret, rotate the signing key. It also records what is missing. There is no bulk lever to end every session at once; a mass logout today means one call per user, and the playbook says not to improvise SQL for it under pressure.
The recovery drills found one more trap worth knowing before you need it: restoring an older database dump silently un-suspends everyone suspended after that dump, because the revocation markers live in the same database. Reconciling that needs an off-host copy of the audit stream.
The issuer also lets my own tools sign in
Two smaller pieces show what a shared identity layer makes cheap.
A captureSession() plugin in the Hono SDK lets my capture and feedback tooling sign in to my own apps to take screenshots and page snapshots. The tool's worker signs a single-use Ed25519 token for one origin (valid for at most 120 seconds), the app exchanges it for a five-minute session for one designated user, and the worker installs that cookie only for that origin. Sedule's decision record adds the rule that matters most: the capture user is a read-only team member with demo data, never a real customer. Sedule, Attest and Loopa added it on the same day.
A FastAPI reference client proves the issuer is usable outside the Hono stack. It uses Authlib for the OIDC client and keeps tokens on the server; the decision record rejected a browser app that holds bearer tokens and calls FastAPI directly.
What I would tell a team considering this
FAQ
Do I need a central identity provider for two products?
Probably not. The overhead (an issuer to deploy, back up, monitor and upgrade) pays off once people move between products, or once you need one place to suspend someone.
Why Better Auth for the issuer?
The products already used it, and its OAuth provider plugin covers OAuth 2.1 and OIDC with PKCE and consent.
Does each product still need its own users table?
Yes, in this design. The product maps issuer, client and subject to its own user and keeps its own permissions, so the issuer never decides what someone may do inside a product.
How fast does a suspension reach the products?
About 63 seconds at the default 60-second check while the issuer is reachable, and at most 363 seconds when it is not, after which the product denies the session.
4.2 to 5.6 seconds in real Chromium, WebKit and Firefox
Issuer unreachable
TTL plus the allowed staleness plus the timeout (363 seconds at the defaults), then the product denies the session
Product cold start while the issuer is down
denied
Measure the revocation delay before anyone asks. "About a minute, at most six minutes during an outage, then closed" is a concrete answer a buyer can put into a security review.
Test in production mode, behind the real proxy. Two of the three gaps above existed only when NODE_ENV=production or only behind the proxy.
Put security checks at endpoints you own. Hooks and middleware inside a library's request path can be skipped by the library.
Decide linking rules before the first integration. No implicit linking by email, a fresh session to link, and a hard stop when a central identity matches an unlinked local account.
Budget for lockstep upgrades. A shared SDK that peer-pins its auth library turns one upgrade into one per product.
The managed and self-hosted options in Neon Managed Better Auth in Next.js on Vercel and OAuth for MCP Server: Complete Guide to Protecting Claude cover a single application. Once several products share users, the issuer becomes one more product you operate, with its own runbooks, drills and on-call questions, and in exchange each new product gets sign-in, revocation and an audit trail from the start.