Guide
Setting up Auth Server
From docker compose up on your machine to a Helm release in your cluster, one step at a time, with screenshots of the server at each one.
Before you start
The guide goes from a server on your machine to one in a Kubernetes cluster, in the order you'd set it up. Each part stands on its own, so skip to the one you need.
| For | You need |
|---|---|
| Running it locally | Docker, Node.js 26 and pnpm 12 |
| Production | A PostgreSQL 17 database, an SMTP server, and HTTPS in front of the server |
| Kubernetes | Helm 3.8 or later (OCI charts), an ingress controller, cert-manager |
Every setting is an environment variable, checked when the server starts: a missing or wrong one stops it with a message naming the variable. The full list, with a line on each, is .env.example.
Run it locally with Docker Compose
The repository's compose.yaml runs PostgreSQL for development, on the loopback address only. The server and the example app run on your machine, in development mode.
Clone it and install
Terminalgit clone https://github.com/sajanv88/authserver-oidc.git cd authserver-oidc pnpm installCreate your .env
Copy the example, then set
BETTER_AUTH_SECRET(at least 32 random characters) andSEED_ADMIN_PASSWORD(at least 12). Everything else has a working default for development.Terminalcp .env.example .env openssl rand -base64 32 # paste it as BETTER_AUTH_SECRETStart PostgreSQL
Terminaldocker compose up -d # Port 5432 taken? Pick another one, and use it in DATABASE_URL: # POSTGRES_PORT=55432 docker compose up -dCreate the tables
Terminalpnpm db:migrateSeed an admin and the example app
Terminalpnpm db:seedIt prints the example app's client ID: put it in
.envasEXAMPLE_CLIENT_ID, with a randomEXAMPLE_SESSION_SECRET. The next part says what the seed does.Start everything
Terminalpnpm devAddress What it is http://auth.localtest.me:3000The auth server http://app.localtest.me:3001The example app, which signs in with it http://localhost:3002This site localtest.meand its subdomains point at your own machine, so the server and the app get two names on one cookie domain without editing your hosts file. Emails are printed in the terminal, links included.

The first admin
Admins register the apps that sign people in. Nobody can make themselves one: sign-up can't set the role, so the first admin is made directly in the database.
On your machine: the seed
pnpm db:seed creates SEED_ADMIN_EMAIL (by default admin@localtest.me) with SEED_ADMIN_PASSWORD, its email already confirmed, and registers the example app as a public client. It goes through the same code as a sign-up, it's safe to run twice, and it refuses to run with NODE_ENV=production.

In production: one SQL statement
Sign up
Create your account on
/signupand confirm your email, as anyone would.Make it an admin
psqlupdate users set role = 'admin' where email = 'you@example.com';Sign in again
Sign out and back in. OIDC clients appears in the bar.
pnpm clients:provision clients.json as PROVISION_ADMIN_EMAIL. It creates what's missing and updates what changed, but never deletes. The scopes and APIs parts show a file.Sign-in with Google, Microsoft, GitHub or your own OIDC provider
Each provider is off until its client ID and its secret are both set; setting only one of the two stops the server at startup. Turn on as many as you like: each gets a button above the email form, on the sign-in and sign-up pages.
Register the auth server with the provider
Create an OAuth app (Google Cloud Console, Microsoft Entra ID, GitHub's developer settings, or your identity provider) and give it this redirect URI, with your own
BETTER_AUTH_URL:Redirect URIhttps://auth.example.com/api/auth/callback/<google | microsoft | github | sso>Set its client ID and secret
Provider Set Notes Google GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRETA Web application client. Microsoft MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET, MICROSOFT_TENANT_IDThe tenant is common, organizations, consumers, or your tenant's ID. GitHub GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRETAn OAuth app, with the redirect URI as its callback URL. Any OIDC provider SSO_NAME, SSO_DISCOVERY_URL, SSO_CLIENT_ID, SSO_CLIENT_SECRETOkta, Keycloak, Auth0, Entra ID… All four or none; the button says Continue with SSO_NAME. .envGOOGLE_CLIENT_ID=1234567890-abc.apps.googleusercontent.com GOOGLE_CLIENT_SECRET=GOCSPX-... GITHUB_CLIENT_ID=Iv1.0123456789abcdef GITHUB_CLIENT_SECRET=...Restart, and sign in
The buttons appear on the next start. An app signing someone in through the auth server sees no difference: the same ID token, whichever way they signed in.

How accounts are matched
- A provider's sign-in joins an existing account with the same email only when both addresses are confirmed. Otherwise it's refused, rather than handing someone else the account.
- Microsoft: a work account's email is trusted only from the one tenant
MICROSOFT_TENANT_IDnames, or when the app registration adds the optionalxms_edovclaim. Any organisation's admin can set any address on their own users. - An account with two-factor on signs in with its password and code: a provider's sign-in is refused for it, because the provider can't ask for the second factor.
- Someone who only ever used a provider can add a password through
Forgot password, as their profile page says.
*_CLIENT_SECRETs belong in your secret store, next to BETTER_AUTH_SECRET. In Kubernetes they go in the Secret, as the last part shows.Scopes
A scope is something an app asks for and the user agrees to on the consent screen. Four come with OpenID Connect; you add your own for your APIs.
| Scope | What the app gets |
|---|---|
openid | An ID token: who signed in (sub). Every sign-in asks for it. |
profile | Their name and picture. |
email | Their email address, and whether it's confirmed. |
offline_access | A refresh token, so the app can stay signed in. It rotates on every use. |
crm, booking… | Your API scopes, from OAUTH_API_SCOPES. The consent screen describes each one. |
Offer your API scopes
.envOAUTH_API_SCOPES=crm,bookingThey're published in discovery (
scopes_supported) beside the four above.Give them to the apps that need them
An app may ask only for the scopes it was registered with: anything else is refused with
invalid_scope. Give a client its scopes in the provisioning file (next part).Ask for them at sign-in
The authorization requestscope=openid profile email offline_access crm

Your APIs (resources)
An API that trusts the auth server needs an access token meant for it, and only for it. Name each API by its URL (an RFC 8707 resource): a token asked for with that resource is a signed JWT whose audience is that API, which it checks against the published keys with no call to the auth server.
List your APIs
.envOAUTH_RESOURCES=https://api.example.com OAUTH_API_SCOPES=crm,bookinghttps in production. They're added to the database when the server starts; removing one from the list doesn't delete it.
Link each app to the APIs it may call
Only a linked app gets a token for an API; any other is refused with
invalid_target. Awebclient signs people in; amachineclient is a service calling the API as itself.clients.json{ "clients": [ { "type": "web", "name": "Acme CRM", "redirectUris": ["https://crm.example.com/callback"], "scopes": ["crm"], "resources": ["https://api.example.com"] }, { "type": "machine", "name": "Nightly jobs", "scopes": ["crm"], "resources": ["https://api.example.com"] } ] }Terminalpnpm clients:provision clients.json # Acme CRM: created (client ID <its client ID>) # client secret, shown only now: <its secret>Ask for a token for the API
Add
resourceto the token request (or the authorization request). A service uses client credentials:Terminalcurl -X POST https://auth.example.com/api/auth/oauth2/token \ -u "$CLIENT_ID:$CLIENT_SECRET" \ -d grant_type=client_credentials \ -d scope=crm \ -d resource=https://api.example.comCheck it in the API
require-token.tsimport { createRemoteJWKSet, jwtVerify } from "jose"; const issuer = "https://auth.example.com"; const keys = createRemoteJWKSet(new URL("/jwks", issuer)); export async function requireToken(authorization: string | undefined, scope: string) { const token = authorization?.match(/^Bearer (.+)$/)?.[1]; if (!token) throw new Error("No access token"); const { payload } = await jwtVerify(token, keys, { issuer, audience: "https://api.example.com", // this API algorithms: ["RS256"], }); if (!String(payload.scope).split(" ").includes(scope)) throw new Error("Missing scope"); return payload; // sub for a person, client_id for a service }
Without a resource
A token asked for without resource is opaque: for /oauth2/userinfo and introspection, not for your APIs.
backchannelLogoutUri in the file, and when a user's session ends here, the app is sent a signed logout token for it (for sessions where it holds a refresh token).Register an app
Every app that signs people in is registered by an admin, with the exact redirect URIs it may return to. There's no self-service registration.
| Kind | For | Secret |
|---|---|---|
| Public | Single-page apps, mobile and desktop apps: anything a user can read the code of | None: PKCE alone proves it's the same app |
| Confidential | Apps with a server that keeps a secret: Next.js, Rails, Django… | A client secret, sent with Basic auth |
Open OIDC clients, then New client
Give it a name, pick its kind, and list its redirect URIs, one per line, https in production.

A confidential client for a server-side app. Copy its credentials
The client ID goes in the app's configuration; for a confidential client, so does the secret. It's shown once: copy it now.

The secret is stored hashed: if it's lost, rotate it for a new one. Point the app's OIDC library at the issuer
The app's .envOIDC_ISSUER=https://auth.example.com OIDC_CLIENT_ID=your-client-id OIDC_CLIENT_SECRET= # only for a confidential client OIDC_REDIRECT_URI=https://app.example.com/oidc/callback OIDC_SCOPES="openid profile email offline_access"Most libraries need nothing else: they read the endpoints from
/.well-known/openid-configuration.
PKCE, step by step
Every sign-in uses the authorization code flow with PKCE (S256), public and confidential clients alike; a request without it is refused. Your library does this for you. By hand, it goes like this.
Make a verifier and its challenge
pkce.tsimport { createHash, randomBytes } from "node:crypto"; const verifier = randomBytes(32).toString("base64url"); // keep it until the callback const challenge = createHash("sha256").update(verifier).digest("base64url");Send the user to /authorize with the challenge
RedirectGET https://auth.example.com/api/auth/oauth2/authorize ?response_type=code &client_id=your-client-id &redirect_uri=https%3A%2F%2Fapp.example.com%2Foidc%2Fcallback &scope=openid%20profile%20email%20offline_access &state=RANDOM_STATE &nonce=RANDOM_NONCE &code_challenge=THE_CHALLENGE &code_challenge_method=S256Keep the state, the nonce and the verifier (encrypted, in a cookie or the session) until the user comes back.
Swap the code, with the verifier
Terminal# A public client sends its client_id; a confidential one adds -u "$CLIENT_ID:$CLIENT_SECRET". curl -X POST https://auth.example.com/api/auth/oauth2/token \ -d grant_type=authorization_code \ -d code=CODE_FROM_THE_CALLBACK \ -d redirect_uri=https://app.example.com/oidc/callback \ -d client_id=your-client-id \ -d code_verifier=THE_VERIFIERCheck the state first. The answer has an RS256 ID token, an access token, and with
offline_accessa refresh token. Verify the ID token against/jwksand check it carries your nonce before you trust it.
Optional: push the request first (PAR)
With pushed authorization requests (RFC 9126), the app's server posts the same parameters to /oauth2/par, authenticated as at the token endpoint, and sends the browser to /authorize with only its client ID and a one-time request_uri, good for 60 seconds. The request is checked before the user sees anything, and can't be altered on the way.
curl -X POST https://auth.example.com/api/auth/oauth2/par \
-u "$CLIENT_ID:$CLIENT_SECRET" \
-d response_type=code \
-d redirect_uri=https://app.example.com/oidc/callback \
-d scope="openid profile email" \
-d state=RANDOM_STATE \
-d code_challenge=THE_CHALLENGE \
-d code_challenge_method=S256
# 201 {"request_uri":"urn:ietf:params:oauth:request_uri:…","expires_in":60}
# Then: /api/auth/oauth2/authorize?client_id=your-client-id&request_uri=<that request_uri>Signing out here too
Clearing the app's own cookie signs someone out of the app, but not of this server: their next sign-in goes straight through. To end both, the app clears its session, then sends the browser to the end-session endpoint with the ID token it kept. The server ends that session, tells apps with back-channel logout, and sends the browser back.
GET https://auth.example.com/api/auth/oauth2/end-session
?id_token_hint=THE_ID_TOKEN
&client_id=your-client-id
&post_logout_redirect_uri=https%3A%2F%2Fapp.example.com%2F
&state=OPTIONAL_STATEIt goes back only to an address registered for the app, exactly: give the app postLogoutRedirectUris in the provisioning file. Without one, or with an address it doesn't know, the person lands on the server's own "Logged out" page. Without the ID token, the server asks the person to confirm first, so no other site can sign them out.
Confidential clients and their secrets
- A confidential client authenticates with HTTP Basic auth (
client_secret_basic): its client ID and secret in theAuthorizationheader, at the token, PAR, revocation and introspection endpoints. - The server keeps only a hash. Nobody, admins included, can read a secret back: it's shown once, when it's made.
- Lost or leaked? Rotate secret in the client's menu. The old one stops working at once, so update the app straight after.
- Keep it with the app's other secrets (a secret manager, a Kubernetes Secret), never in its code or in a browser bundle. An app that can't keep a secret is a public client.
machine client only uses client credentials, within the scopes it was given; it can't sign anyone in. A web client can't use client credentials.Security
Most of it is on from the first start. A few settings are yours, because they depend on where the server runs.
On by default
- PKCE (S256) on every sign-in; no implicit flow, no device flow, no self-registration.
- RS256 ID tokens that last 10 minutes, access tokens too; refresh tokens last 30 days and rotate on each use, and reusing a spent one revokes its whole family.
- Client secrets and pushed requests stored as hashes, not values.
- A nonce-based Content Security Policy on every page,
form-action 'self', and the usual security headers. - Rate limits per client IP on sign-in, sign-up, codes, tokens and every email (5 sign-ins a minute, 30 token requests a minute).
- Sign-up, password reset and sign-in links answer the same whether or not an account exists, and in the same time: emails are rendered and sent after the response.
Yours to set
| Setting | Set it to |
|---|---|
BETTER_AUTH_SECRET | At least 32 random characters, from a secret store. It signs sessions and the requests carried between sign-in steps. |
BETTER_AUTH_URL | Your https origin, with no path: it's also the OIDC issuer. Production refuses http. |
TRUSTED_ORIGINS | Every app origin that calls the server, exactly, https in production. No wildcards. |
TRUSTED_PROXIES | Your proxy's or ingress pods' addresses (IPs or CIDRs). The client IP for rate limiting is the rightmost X-Forwarded-For hop that isn't one of them: left empty, every request seems to come from the proxy. |
COOKIE_DOMAIN | Only if apps on sibling subdomains should share the session cookie. Every subdomain then receives it, so only for apps you fully trust. |
TURNSTILE_SITE_KEY, TURNSTILE_SECRET_KEY | Optional: Cloudflare Turnstile on every form and the endpoints behind them. Both or neither. |
TWO_FACTOR_REQUIRED_FOR_ADMINS | Optional: true makes every admin set up two-factor before anything else, apps included. |
openssl rand -base64 32What your users get
Under My profile, everyone can change their password (which signs out their other devices), turn on two-factor authentication with any authenticator app and ten backup codes, and see and end their sessions.


Managing people
Admins find anyone under Users, by name, email or status, and open them to:
- Disable the account, for a day, a week, a month or until enabled again. It can't sign in by any method, its sessions end, and every token its apps hold is revoked, offline access included.
- Sign them out everywhere, with the same revocation, for a lost laptop or someone leaving.
- Require two-factor: until it's on, every page and every app's sign-in sends them to set it up first. Reset it for a lost phone.
- Make them an admin, or a user again, and delete the account once its email is typed, for a GDPR request.
The person gets an email when their account is disabled, enabled, deleted, or its two-factor is reset. Each change is kept in the account's history: what, when and by whom. No admin can do these to their own account.

Email over SMTP
The server sends four emails: confirm your address, reset your password, a sign-in link, and "you already have an account" to someone who signs up twice. In development they're printed in the terminal; in production they go out over SMTP, which the server requires.
Set the SMTP server
Setting What it is EMAIL_PROVIDERsmtp in production; console only logs them EMAIL_FROMThe sender, such as Acme ID <no-reply@example.com> SMTP_HOSTYour SMTP server, such as Cloudflare's or your provider's SMTP_PORT465 for TLS from the first byte; any other port must offer STARTTLS SMTP_USERIts user name SMTP_PASSWORDIts password or API token: a secret .envEMAIL_PROVIDER=smtp EMAIL_FROM="Acme ID <no-reply@acme.example.com>" SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_USER=apikey SMTP_PASSWORD=...Brand them
APP_NAMEis the name in every subject, heading and sign-off, andLOGO_URLputs your logo beside it (not an SVG, which Gmail and Outlook don't show).Send one
Ask for a password reset on
/forgot-password. Each email has an HTML part and a plain-text one, made from the same template.

Encrypted, always
The connection is always encrypted, with TLS 1.2 or later and a certificate the server must trust: on any port but 465 it requires STARTTLS, and a server that doesn't offer it is refused. Nothing is ever sent in the clear.
NODE_EXTRA_CA_CERTS=/path/to/ca.crt, rather than turning verification off. That's how the screenshot above was sent.The production image
Each release is an image for amd64 and arm64, public on GitHub's registry: ghcr.io/sajanv88/auth-server:v1.1.5. It runs as an unprivileged user, works with a read-only root filesystem, and answers GET /api/health without touching the database, for probes.
Write its settings
Production needs https, SMTP and a database. In
auth.env, or your platform's secrets and variables:auth.envDATABASE_URL=postgres://auth:...@db.example.com:5432/auth?sslmode=verify-full BETTER_AUTH_SECRET=... # openssl rand -base64 32 BETTER_AUTH_URL=https://auth.example.com TRUSTED_ORIGINS=https://app.example.com TRUSTED_PROXIES=10.0.0.5 # your TLS proxy EMAIL_PROVIDER=smtp EMAIL_FROM="Acme ID <no-reply@example.com>" SMTP_HOST=smtp.example.com SMTP_PORT=587 SMTP_USER=apikey SMTP_PASSWORD=... APP_NAME=Acme IDRun the migrations
The image carries its own migration runner. Run it before every new version.
Terminaldocker run --rm --env-file auth.env ghcr.io/sajanv88/auth-server:v1.1.5 \ node packages/db/dist/migrate.mjsStart it, locked down
Terminaldocker run -d --name auth-server --env-file auth.env -p 127.0.0.1:3000:3000 \ --read-only --tmpfs /app/apps/auth-server/.next/cache:uid=1001,gid=1001 \ --cap-drop ALL --security-opt no-new-privileges \ ghcr.io/sajanv88/auth-server:v1.1.5Put HTTPS in front of it
Your proxy terminates TLS for
BETTER_AUTH_URLand forwards to port 3000 withX-Forwarded-ForandX-Forwarded-Proto: https. Name it inTRUSTED_PROXIES.
compose.yaml, behind a TLS proxy, with SMTP over STARTTLS, and the admin from the seed.Deploy to Kubernetes
The Helm chart is published with each release at oci://ghcr.io/sajanv88/charts/auth-server, at the release's version. It runs the image as above, with probes, a disruption budget, zone spreading and an optional autoscaler, and its values.yaml explains every setting.
Create the Secret
The chart never creates secrets: it reads them from one you make, named by
existingSecret(auth-server-secretsby default). Use External Secrets or Sealed Secrets in a real cluster; by hand:Terminalkubectl create namespace auth kubectl -n auth create secret generic auth-server-secrets \ --from-literal=BETTER_AUTH_SECRET="$(openssl rand -base64 32)" \ --from-literal=DATABASE_URL='postgres://auth:...@db.example.com:5432/auth?sslmode=verify-full' \ --from-literal=SMTP_PASSWORD='...' # With Turnstile or sign-in providers on, add TURNSTILE_SECRET_KEY and each *_CLIENT_SECRET.Write your values
Everything that isn't a secret goes in
config; the chart renders it into a ConfigMap, and a change rolls the pods.values.auth.yamlingress: enabled: true className: nginx annotations: cert-manager.io/cluster-issuer: letsencrypt-prod hosts: - host: auth.example.com paths: - path: / pathType: Prefix tls: - secretName: auth-server-tls hosts: [auth.example.com] config: BETTER_AUTH_URL: https://auth.example.com COOKIE_DOMAIN: "" # or .example.com, to share the session cookie TRUSTED_ORIGINS: https://app.example.com TRUSTED_PROXIES: 10.0.0.0/8 # your ingress controller's pod network EMAIL_FROM: "Acme ID <no-reply@example.com>" SMTP_HOST: smtp.example.com SMTP_PORT: "587" SMTP_USER: apikey APP_NAME: Acme ID OAUTH_RESOURCES: https://api.example.com OAUTH_API_SCOPES: crm,booking autoscaling: enabled: true minReplicas: 3 maxReplicas: 10Install it
Terminalhelm install auth-server oci://ghcr.io/sajanv88/charts/auth-server \ --version 1.1.5 -n auth -f values.auth.yaml kubectl -n auth rollout status deploy/auth-serverThe image is public, so the cluster needs no pull secret. The chart's
values-production.yamlnames one (ghcr-pull) for a private copy: leave it out, or setimagePullSecrets: [].Make the first admin
Sign up at your
BETTER_AUTH_URL, then promote the account as in The first admin.
Migrations, and Argo CD
The chart's migration Job is an Argo CD PreSync hook: with Argo CD it runs, and must succeed, before the new pods are applied. Plain Helm treats it as an ordinary Job, created with the Deployment: that's fine for the first install, but for an upgrade that changes the schema, run it first, or deploy with Argo CD.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: auth-server
namespace: argocd
spec:
project: default
source:
# Registered in Argo CD as a Helm repository with OCI enabled.
repoURL: ghcr.io/sajanv88/charts
chart: auth-server
targetRevision: 1.1.5
helm:
valuesObject:
config:
BETTER_AUTH_URL: https://auth.example.com
# ...the rest of values.auth.yaml
destination:
server: https://kubernetes.default.svc
namespace: auth
syncPolicy:
automated: { prune: true, selfHeal: true }TRUSTED_PROXIES covers your ingress pods (otherwise every user shares one rate limit), that the database URL verifies TLS, and that replicas × DATABASE_POOL_MAX stays under your database's connection limit.