JWT
JwtStrategy verifies a bearer token against a secret, an EdDSA public key or an external issuer's JWK Set, and JwtService signs with the first two.
JSON Web Tokens are the framework’s default bearer credential.
JwtStrategy<C> is generic over the claims type — your app picks the
shape, the framework verifies the signature, checks expiry, and hands
the claims to the handler. Signing and verifying both run through
JwtService, configured once via AuthnConfig and injected wherever a
token is minted.
The implementation is a thin wrapper over
jsonwebtoken, which your code never names:
the algorithms are nestrs’s own Algorithm, spelled as RFC 7518 spells
alg — RS256, ES256, EdDSA — so a release of the library reaches you
in a nestrs minor.
The three-line setup
Section titled “The three-line setup”A resource-server app declares a type alias and a tiny module:
use nest_rs::authn::JwtStrategy;
use super::Claims;
pub type AuthnStrategy = JwtStrategy<Claims>;
pub type AuthnGuard = nest_rs::authn::AuthnGuard<AuthnStrategy>;use nest_rs::core::module;
use super::strategy::{AuthnGuard, AuthnStrategy};
#[module( imports = [nest_rs::authn::AuthnModule], providers = [AuthnStrategy, AuthnGuard],)]pub struct AuthnModule;AuthnModule reads AuthnConfig from the environment;
pass an AuthnConfig to pin it in code. The factory phase builds
JwtService once and registers it as global infrastructure —
controllers, login services, OAuth flows all inject the same instance.
Three env vars make it work end to end — a shared HS256 secret (32 bytes minimum; anything shorter fails the boot), and the issuer and the audience every token names, here the app’s own origin, since it both mints and verifies:
export NESTRS_AUTHN__SECRET="$(openssl rand -hex 32)"export NESTRS_AUTHN__ISSUER='https://api.example.com'export NESTRS_AUTHN__AUDIENCE='https://api.example.com'With those set, JwtService signs and verifies against the same
secret: AuthnGuard returns a 401 without a valid
Authorization: Bearer token and attaches the claims otherwise. An app
naming no issuer or no audience does not start
(RFC 9068); a scaffolded one names both, its own
origin, in apps/<app>/.env. Every other knob is optional — the full env
table and the HS256-vs-EdDSA decision are on
JWT configuration.
What JwtStrategy does
Section titled “What JwtStrategy does”JwtStrategy<C> is an #[injectable] over an Arc<JwtService> and a
PhantomData<C>. On each request it:
- Pulls
Authorization: Bearer <token>out of the headers viabearer_token. - Calls
JwtService::verify::<C>(token)to verify the signature, checkexp/nbf, and deserialize the claims. - Returns
Ok(claims)on success.
A missing header yields AuthError::MissingCredentials; a bad
signature yields AuthError::InvalidSignature; an expired token
yields AuthError::Expired. AuthnGuard maps every variant to a 401
with WWW-Authenticate: Bearer.
Claims — your shape, your business rules
Section titled “Claims — your shape, your business rules”The framework’s JwtStrategy<C> is generic. C is any
DeserializeOwned + PrincipalIdentity + AmbientValue + Clone type — usually a
struct with the standard sub plus whatever your app needs, which derives the
two traits. exp is the signer’s, so the struct needs no field for it:
use nest_rs::authn::PrincipalIdentity;use serde::{Deserialize, Serialize};use uuid::Uuid;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(from = "String", into = "String")]pub enum Subject { User(Uuid), Client(String),}// …
#[derive(Clone, Debug, Serialize, Deserialize, PrincipalIdentity)]pub struct Claims { #[principal(actor)] pub sub: Subject, pub client_id: String, #[principal(tenant)] pub org_id: Uuid, pub roles: Vec<Role>,}#[derive(PrincipalIdentity)] reads each role off the field marked for it.
#[principal(actor)] is the audit identity: on a successful authentication
AuthnGuard records it as actor_id onto the request span, so every
downstream event — denials included — is attributable without threading the
identity through each call site. #[principal(tenant)] is the tenant the
caller acts within, made ambient for the request and every job it pushes
(Multi-tenant SaaS), and #[principal(scopes)]
the token’s scope claim (Scopes); both are
optional. An actor or a tenant is read as the text its value prints, so a
Uuid, a String or an enum with its Display all serve, and an Option
answers None when it holds none. The derive also implements AmbientValue,
which is what lets AuthnGuard attach the claims for the rest of the request —
every guard after it, and Ambient<Claims> in a handler on any edge, a resolver
below /graphql included, read them there. Claims marking no actor, or a role
the derive does not know, are a compile error naming the three roles it takes;
a role marked twice is refused at its second mark. A generic principal, or one
narrowing what it carries, writes the two impls by hand.
Every access token names its subject: RFC 9068 §2.2 requires sub, the user’s
id, or the client’s own when it acts on its own behalf (the
client_credentials grant). So sub is never optional, a token without one is
refused before any route, and actor_id always returns it — which is what an
MCP session
binds to. Subject keeps the two kinds apart: one string on the wire, read
back by its shape, a UUID being a user. The registry of your clients therefore
refuses a client id a UUID parses, so no client passes for a user (RFC 9068
§5): with nest_rs::oauth::server, a module-init hook of yours over
OAuthServerConfig, since the scheme reading a subject is yours
(Token endpoint).
A route writing a user’s row reads claims.sub.user_id(), which a client
answers with None. nestrs g auth writes the enum, its conversions
and the struct with its derive.
The handler reads them back through Ambient<Claims>:
async fn caller_org(&self, auth: Ambient<Claims>) -> Json<Uuid> { Json(auth.org_id)}A create needs no Ambient<Claims> to land in the caller’s org: the Create grant
that pins org_id also fills it (Entity inputs).
Signing a token
Section titled “Signing a token”A login or OAuth callback injects Arc<JwtService> and calls sign; what it
stamps, what it refuses to mint and sign_for’s audience are on
Signing a token.
Verifying outside the guard
Section titled “Verifying outside the guard”Most code reaches the claims through Ambient<C>. A path that needs to
verify an access token manually — say, a queue job carrying a signed envelope —
injects Arc<JwtService> and calls verify, which refuses a handshake token such as
the OAuth transaction cookie; that one takes verify_handshake:
let claims: Claims = self.jwt.verify(token).await?;verify is async because a JWK Set may have to be fetched first; against a
secret or a PEM key it never waits. The verification path runs Validation::leeway, checks nbf, and
applies RFC 9068 §4
to iss and aud always: each is required and must name the configured
issuer and this app’s audience, so a token naming another, or none, is
rejected — allow_any_audience alone lifts the audience half. A token its
issuer bound to a key, carrying cnf, is refused as AuthError::SenderConstrained:
verify reads a bearer token, which proves no key
(Split deployment).
Verification failures here log at tracing::debug! under nest_rs::authn,
carrying the typed decode reason — and an expired token logs nothing at all.
Both follow from “one event, said once”: the single warn for an
authentication failure is the guard’s, which has the strategy and the route to
name, so a second line from the service would double-count every denial.
Configuration
Section titled “Configuration”Every AuthnConfig field, the key mode its keys pick, the issuer and audience
it requires and the choice between HS256, EdDSA and a JWK Set are on
JWT configuration.
Verifying another issuer’s tokens
Section titled “Verifying another issuer’s tokens”When an identity provider you do not run issues the tokens — better-auth,
Keycloak, Auth0, Cognito, Entra ID, Google, Firebase, Clerk, Zitadel — point
the resource server at the JWK Set
(RFC 7517) it publishes, the
jwks_uri of its discovery document:
export NESTRS_AUTHN__JWKS_URI='https://auth.example.com/.well-known/jwks.json'export NESTRS_AUTHN__ISSUER='https://auth.example.com'export NESTRS_AUTHN__AUDIENCE='https://api.example.com'Nothing else changes: JwtStrategy verifies, the claims reach Ambient<C>,
iss, aud and exp are checked as above. The service holds no signing key,
so sign refuses, and so do sign_handshake and verify_handshake: an OAuth
flow’s transaction cookie needs a key of this deployment’s own. An issuer that stamps no typ: at+jwt on its access tokens
also needs <PREFIX>_AUTHN__EXPLICIT_TYPING=false — read one token’s header to
know. External identity provider
walks the whole setup with better-auth.
What a token may be signed with is the verifier’s choice, never the
token’s (RFC 8725 §3.1).
Each key checks only an algorithm of its own type — an RSA key RS256 to RS512
and PS256 to PS512, an EC P-256 key ES256, P-384 ES384, Ed25519 EdDSA — and
only the alg it names when it names one. A key published with a use other
than sig is ignored. No HS* or none token is ever accepted against a
JWK Set, and such a token is refused before the set is fetched.
<PREFIX>_AUTHN__ALGORITHMS narrows the list to what your issuer signs with —
EdDSA, RS256 — which also binds a key published without alg to that one
algorithm.
The token’s kid picks the key. A token naming no kid is checked only when
exactly one key of the set fits its algorithm, never tried against each.
The set is fetched when the first token needs it, not at boot: an issuer
down while the API deploys does not crash-loop the API. Tokens arriving during
a fetch wait for that one fetch; a kid the set lacks earns one more, so a
rotation is picked up with the first token signed by the new key. The bounds
are constants of nest_rs::authn:
| Constant | Value | What it bounds |
|---|---|---|
JWKS_FETCH_TIMEOUT | 5 s (3 s to connect) | one fetch, body included — a token waits on one at most |
JWKS_MAX_BYTES | 128 KiB | the document read; a longer one is refused unread |
JWKS_REFRESH_FLOOR | 30 s | the least time between two fetches, whatever asks — a flood of forged kids costs the issuer one request per floor |
JWKS_RETRY_AFTER_CEILING | 1 h | how much of an issuer’s Retry-After, on a 429 or a 5xx, is counted; what it asks is waited, stretched by up to a fifth so replicas it told together come back apart: the next fetch is held back 72 min at most |
JWKS_DEFAULT_MAX_AGE | 10 min | how long a set stays fresh when the answer states no Cache-Control: max-age; a stated one is honoured, net of Age, from the floor to JWKS_MAX_AGE_CEILING (1 h) |
JWKS_STALE_CEILING | 1 h | how long past its freshness the last good set still verifies while every refresh fails |
A stale set keeps serving while it refreshes, and a refresh that fails is said
once at warn on nest_rs::authn while the last good set is kept. A set that
cannot be had — never fetched, past its stale ceiling, or failing while the
key a token names is looked for — answers 503 with a Retry-After saying
when the next fetch may start, on a #[public] route too, never a 401: the
token was never checked. The
endpoint must be https, and its certificate is verified against the system’s
authorities, or the ones <PREFIX>_AUTHN__TLS_CA_CERT names; an issuer that
requires a client certificate gets the one <PREFIX>_AUTHN__TLS_CERT and
<PREFIX>_AUTHN__TLS_KEY name, read at the start: a renewed file takes effect
at the next one, so rotate it with a rolling restart. A handshake that fails
answers that same opaque 503, while the line the edge files for it — guard denied the request on nest_rs::authn, at warn — names the setting that
fixes it in its error chain; the fetch follows no redirect.
Going further
Section titled “Going further”- JWT configuration — the keys, the issuer and the audience a verifier requires.
- Split deployment — the split-deploy pattern that pairs with EdDSA.
- External identity provider — the JWK Set path, end to end with better-auth.
- Authorization — once the claims land on
the request, the authz layer builds an
Abilityfrom them.