External identity provider
Verify the access tokens an identity provider you do not run issues — better-auth worked end to end — against the JWK Set it publishes.
Your users sign in somewhere else — a TypeScript app running
better-auth, a Keycloak realm, an Auth0 tenant —
and your nestrs API must accept the access tokens that sign-in hands out. The
API holds no key and mints nothing: it reads the JWK Set the provider
publishes, and JwtStrategy verifies every bearer token against it. This page
does it with better-auth, whose
JWT plugin publishes one; any
provider exposing a jwks_uri takes the same three variables.
You need a better-auth server reachable over https, and the API’s
AuthnModule and JwtStrategy wired as on JWT.
-
Publish the keys from better-auth. Add the
jwt()plugin. It signs with EdDSA over Ed25519 unlessjwks.keyPairConfigsays otherwise, publishes the public keys at/api/auth/jwks, and names the signing key in each token’skidheader. Bothissandauddefault to better-auth’s base URL; set the audience to the API’s own URL, so a token minted for another service is not one this API accepts:auth.ts import { betterAuth } from "better-auth";import { jwt } from "better-auth/plugins";export const auth = betterAuth({plugins: [jwt({jwt: {audience: "https://api.example.com",},}),],});Checkpoint:
curl https://auth.example.com/api/auth/jwksanswers a JSON document whosekeyseach carry akid, analgand the public key. -
Point the API at that set. Three variables name it, the issuer and the audience; two more fit it to how better-auth signs:
Terminal window export NESTRS_AUTHN__JWKS_URI='https://auth.example.com/api/auth/jwks'export NESTRS_AUTHN__ISSUER='https://auth.example.com'export NESTRS_AUTHN__AUDIENCE='https://api.example.com'export NESTRS_AUTHN__ALGORITHMS='EdDSA'export NESTRS_AUTHN__EXPLICIT_TYPING=falseALGORITHMSaccepts the one algorithm better-auth signs with, so no other reaches a key.EXPLICIT_TYPING=falsebecause better-auth’s plugin stamps notypheader on what it mints (plugins/jwt/sign.tsin its source), while the framework asks for RFC 9068’sat+jwtby default. Set noSECRET,PUBLIC_KEYorPRIVATE_KEYbeside them: two key sources fail the boot.Checkpoint: the API boots without asking better-auth for anything — the set is fetched by the first token that needs it.
-
Read the claims better-auth puts in the token.
subis the user’s id unlessjwt.getSubjectsays otherwise; beside it sits the session’s user object, or what yourjwt.definePayloadreturns instead. Read what the API needs:crates/features/src/identity/claims.rs use nest_rs::authn::PrincipalIdentity;use serde::{Deserialize, Serialize};#[derive(Clone, Debug, Serialize, Deserialize, PrincipalIdentity)]pub struct Claims {#[principal(actor)]pub sub: String,pub exp: u64,}Checkpoint: a token from better-auth’s
GET /api/auth/token, sent by a signed-in browser, reaches a guarded route; the same request without it answers401.Terminal window TOKEN=$(curl -s https://auth.example.com/api/auth/token -H "cookie: $SESSION" | jq -r .token)curl -s https://api.example.com/posts -H "authorization: Bearer $TOKEN" -
Tell OAuth clients where to get a token, when better-auth’s OAuth Provider plugin issues them — to an MCP client, say. Its guide asks the API that receives access tokens to publish OAuth Protected Resource metadata, the RFC 9728 document
OAuthResourceModuleserves; see Protected resource metadata. The provider signs with the same/jwkskeys and puts theresourcea client asked for in the token’saud, which the module requires:RESOURCEis the audience, so step 2’sAUDIENCEgoes. Its tokens carry an issuer of its own, under better-auth’s base path, whichAUTHORIZATION_SERVERSnames — the issuer the module requires of a token — so step 2’sISSUERgoes too, or changes to that sameissuerits discovery document names: one the document does not advertise fails the boot.Terminal window export NESTRS_OAUTH__RESOURCE__RESOURCE='https://api.example.com'export NESTRS_OAUTH__RESOURCE__AUTHORIZATION_SERVERS='https://auth.example.com/api/auth'unset NESTRS_AUTHN__ISSUER NESTRS_AUTHN__AUDIENCEIn a workspace
nestrs newmade, delete the two lines it wrote into the app’s ownapps/<app>/.envtoo,<PREFIX>_AUTHN__ISSUERand<PREFIX>_AUTHN__AUDIENCE, both the app’s origin: under the development and test profiles that file is read over the root’s, so what theunsettakes off the process comes back from it.Checkpoint:
curl https://api.example.com/.well-known/oauth-protected-resourcenames better-auth among itsauthorization_servers.
Key rotation needs nothing on this side. better-auth rotates only when its
rotationInterval option is set, keeping the old key for a gracePeriod; a
token signed by the new key names a kid the API has not seen, and the API
fetches the set once more to find it.
What fails if you get it wrong
Section titled “What fails if you get it wrong”Each refusal is a warn on nest_rs::authn carrying a reason, and a 401
with WWW-Authenticate: Bearer error="invalid_token":
EXPLICIT_TYPINGleft on — every better-auth token isreason="invalid_token". Set it tofalse.AUDIENCEthat is not the token’saud—reason="invalid_token"too. better-auth’s default audience is its own base URL: setjwt.audienceas in step 1, orAUDIENCEto that base URL.- Under
OAuthResourceModule, a token whoseissis not one ofAUTHORIZATION_SERVERS—reason="invalid_token": the module accepts only the issuers its document advertises, compared exactly, trailing slash included. AnISSUERit does not advertise fails the boot, naming both variables. JWKS_URInaming another tenant or another provider’s set — every token isreason="unknown_key": the key itskidnames is not in the set, even after the refetch it earned.- An algorithm
ALGORITHMSleaves out —reason="invalid_algorithm", before anything is fetched. - A token the provider bound to a key — DPoP or mutual TLS,
cnfin the token — isreason="sender_constrained": this server reads a bearer token, which proves no key. Have the provider mint this audience a plain one.
An unreachable provider is not a 401: the request answers 503 with
Retry-After, the line is a warn naming the endpoint in its error chain, and a #[public]
route answers the same rather than serving the caller as anonymous. The last
set fetched keeps verifying for an hour past its freshness while the provider
is down; see the bounds.
Going further
Section titled “Going further”- JWT — what a JWK Set is checked for, and every bound on its fetch.
- Split deployment — the same resource server when the issuer is a nestrs app of your own.
- Threat model — what token verification catches, and what it leaves to you.