Split deployment
A single signer issues tokens, every API verifies them — split the deployment, keep the keys asymmetric, never RPC across the boundary.
A single app that both issues tokens and serves protected routes is
fine — the secret stays in one process, the wiring is one
AuthnModule. The pattern fights you when a second deployable joins:
two binaries can either share the signing secret (and any compromise
mints valid tokens for both) or one becomes the issuer and the other
verifies what it produces. nestrs leans hard on the second posture.
apps/auth is the exemplar issuer. apps/api is
the exemplar resource server. They share a Postgres database and the
crates/features code; they never RPC each other.
Two vocabularies meet on this page, so here is which is which. RFC 6749 §1.1
names the roles — authorization server and resource server — and that is
what the crates are named for: nest-rs-oauth-server and
nest-rs-oauth-resource. Below, apps/auth is called the issuer, because
everything that follows is about the signing key, and issuer is RFC 7519
§4.1.1’s own word for whoever holds it — the iss claim in every token it
mints. Same app, two standards, one deployment.
Install
Section titled “Install”The split is a deployment shape; the crates divide once more narrowly, one per
RFC 6749 §1.1 role. Both halves need authn — JwtService signs and verifies,
and that is the question preceding all four roles. Only the issuer needs
oauth-server, which holds the §5.2 token-endpoint codes, the guard that
authenticates a client there — over an authn Strategy, so the feature brings
authn — and the §2.3.1 machine-client registry: none is a
resource server’s credential verdict, and a resource server that compiled them
would carry a token endpoint it never serves.
# the issuer — signs tokens, so it serves a token endpointcargo add nest-rs --features oauth-server
# and, on both halvescargo add nest-rs --features authnBeing discoverable is what stands apart, and it has its own capability: the
RFC 9728 document and the 401 challenge describe the deployment, are served
to callers with no credential at all, and mount an HTTP controller a worker
would never reach.
cargo add nest-rs --features oauth-resourceSo an issuer enables oauth-server, which brings authn; a discoverable resource
server enables oauth-resource, which brings it too; and a queue worker that only
verifies a JWT enables authn alone, and compiles no token endpoint and no discovery
document. The demo enables them all at once, on its workspace’s nest-rs line.
The split
Section titled “The split”| Concern | Issuer (apps/auth) |
Resource server (apps/api) |
|---|---|---|
| JWT private key | Holds it | Never sees it |
| JWT public key | Holds it | Holds it |
| Token endpoints | /token, /login, OAuth callback |
None |
| Protected routes | None | /users, /orgs, /posts, /graphql, … |
| Database | Yes (shared) | Yes (shared) |
| Cross-app calls | None | None |
The two binaries see the same Claims type through the shared
features::authn module. The verifier deserializes a token
the issuer signed; both speak the same struct, no schema drift
possible.
The keys
Section titled “The keys”Use EdDSA. Generate one key pair, store the private PEM on the issuer only, distribute the public PEM to every verifier:
openssl genpkey -algorithm ed25519 -out jwt.pemopenssl pkey -in jwt.pem -pubout -out jwt.pubThen on the issuer:
export NESTRS_AUTHN__PRIVATE_KEY="$(cat jwt.pem)"export NESTRS_AUTHN__PUBLIC_KEY="$(cat jwt.pub)"On every resource server:
export NESTRS_AUTHN__PUBLIC_KEY="$(cat jwt.pub)"# NESTRS_AUTHN__PRIVATE_KEY is unset — the boot picks `eddsa_verify`Each key also reads from a file: <PREFIX>_AUTHN__PUBLIC_KEY_FILE=/run/secrets/jwt.pub
names the path instead of carrying the PEM, which is the form a mounted secret
takes.
AuthnConfig::into_options walks the four key fields and chooses
verify-only mode when only the public key is set. JwtService::sign
on a verify-only service returns SignError, whose chain says
this JwtService is verify-only — no signing key configured — even a buggy resource
server cannot mint a token.
A misconfiguration (PRIVATE_KEY set, PUBLIC_KEY missing) fails the
boot loudly with <PREFIX>_AUTHN__PRIVATE_KEY (or <PREFIX>_AUTHN__PRIVATE_KEY_FILE), or `private_key` in an AuthnConfig or JwtOptions built in code, is set without <PREFIX>_AUTHN__PUBLIC_KEY (or <PREFIX>_AUTHN__PUBLIC_KEY_FILE), or `public_key` in an AuthnConfig or JwtOptions built in code,
and so does a private key beside the public key of another pair. A
<PREFIX>_AUTHN__SECRET left beside either key fails the boot as well, naming
both — whether both come from the environment, from a .env file or from code,
or the environment beside code; a config pinned in code stops .env being read
for the namespace, and the boot names each key it shadows — so moving a service
to EdDSA means removing its secret.
Two main files, one feature set
Section titled “Two main files, one feature set”#[module( imports = [ SeaOrmDatabaseModule, HealthModule, GithubSocialModule, GoogleSocialModule, SignInHttpModule, ],)]pub struct AuthModule;The issuer imports the sign-in controller (SignInHttpModule) — the token
endpoint, the password login and the social redirects — which imports the
throttler its routes bind; its
SignInModule imports the token signer (nest_rs::authn::AuthnModule) and
registers the authorization server’s clients through
OAuthServerModule::<ClientPayload>. It does not import UsersHttpModule — the issuer
mints tokens, not users.
#[module( imports = [ // … SeaOrmDatabaseModule, // … HealthModule, // … OrgsHttpModule, // … UsersHttpModule, // … ], // …)]pub struct ApiModule;The resource server imports every feature controller, and each imports the authz module its guards need. With only the public key in env, its authn loads as verify-only.
Two modules share one name, and the path says which. SignInModule imports
nest_rs::authn::AuthnModule — the framework’s, which provides JwtService and
carries the config seam. features::authz::AuthzModule imports
features::authn::AuthnModule — the product’s own, which wraps that one and adds
the Claims-bound strategy and guard; it owns no configuration, so it has no seam.
Why not RPC
Section titled “Why not RPC”The two binaries deliberately do not talk to each other. They share a
database, and each owns the table it writes to (the issuer owns
users for signin; the resource server reads users for queries —
both go through the same SeaORM model). Cross-app chatter would
reintroduce the latency, the failure modes, and the protocol drift
the split was supposed to avoid.
When a resource server needs to validate something the issuer knows
(say, a refresh token was revoked), put it in the database — the
issuer writes the revocation row, the resource server reads it via
the same Repo. No HTTP between the two.
Run them together
Section titled “Run them together”nestrs run dev auth # issuer on :3001nestrs run dev api # resource server on :3002A round-trip:
TOKEN=$(curl -sX POST http://localhost:3001/login \ -H 'Content-Type: application/json' \ -d '{"email":"admin@acme.test","password":"publish-demo"}' \ | jq -r .access_token)
curl -s http://localhost:3002/users \ -H "Authorization: Bearer $TOKEN" | jq '.[].name'The bearer is signed by the issuer’s private key; the API verifies with the public key. The API has no way to mint that token even if it wanted to.
Binding a token to its resource
Section titled “Binding a token to its resource”Every resource server trusting one issuer verifies with the same public key,
so a signature alone says nothing about which server a token was minted for:
a token stolen from, or sent by mistake to, one API would be accepted by every
other. RFC 8707 closes it by
naming the resource in the token request, and the issuer writes it into the
token’s aud — the one audience the resource server requires.
Each half holds its own word of that contract. A resource server requires its
own audience — <PREFIX>_AUTHN__AUDIENCE, its canonical URI — and the issuer
it trusts, <PREFIX>_AUTHN__ISSUER; it does not start without either:
# apps/api, deployedNESTRS_AUTHN__AUDIENCE=https://api.example.comNESTRS_AUTHN__ISSUER=https://auth.example.comThe issuer mints each access token for the resource it was asked for, with
JwtService::sign_for(resource, &claims) — never with its own audience, which
is for the tokens it mints for itself, its OAuth transaction cookie among them.
A machine client names the resource in the resource parameter of its token
request, and gets a token only for a resource it is registered for
(AuthenticatedClient::audience_for, which refuses anything else as RFC 8707’s
invalid_target); the demo’s sign-in takes resource the same way, and a
sign-in naming none is minted for the first resource the issuer serves:
TOKEN=$(curl -sX POST http://localhost:3001/login \ -H 'Content-Type: application/json' \ -d '{"email":"admin@acme.test","password":"publish-demo","resource":"http://localhost:3003"}' \ | jq -r .access_token)That token opens the assistant and every other resource server refuses it,
because each app requires an audience of its own — which takes a configuration
of each app’s own. Deployed, a per-process environment is one: the demo’s chart
sets AUTHN__AUDIENCE to each app’s origin and hands the signing key to auth
alone. Run locally, each app’s own apps/<app>/.env is
(an app’s own files): the
demo’s api requires http://localhost:3002, the live app :3004, and the
signing key sits in auth’s own .env.development and .env.test alone.
Telling clients where the issuer is
Section titled “Telling clients where the issuer is”OAuthResourceModule serves the RFC 9728 document naming the issuer, and
points every 401 the app emits at it:
Protected resource metadata.
Going further
Section titled “Going further”- JWT —
AuthnConfig,JwtKey, EdDSA vs HS256. - OAuth2 — the flow the issuer exposes upstream.
- Threat model — what the asymmetric split buys you, and what it does not.