Authentication
A Strategy turns a request into a principal — bearer tokens, OAuth redirects, basic credentials. AuthnGuard runs it and Ambient<P> reads it back.
Authentication answers one question: who is calling. The shape of
the answer is up to the Strategy — a JWT in the Authorization
header, an OAuth provider redirect, a basic-auth client_id:secret,
something app-specific. AuthnGuard<S> runs the strategy on every
request its controller covers, returns a 401 when it fails, and
attaches the principal to the request so the handler reads it back with
Ambient<Principal>.
The framework ships JwtStrategy
(JSON Web Tokens), an
OAuth2 client, and
Argon2id password helpers.
Anything else is a Strategy you write yourself.
Install
Section titled “Install”cargo add nest-rs --features authnBind the shipped JWT strategy
Section titled “Bind the shipped JWT strategy”The common case writes no strategy at all. AuthnGuard<S> is generic
over the strategy, and the framework ships
JwtStrategy — a resource-server app
ships two short files — the aliases, and the module that provides them:
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;Bind the guard on the controller, and every route under it requires a valid principal:
#[controller(path = "/users")]#[use_guards(AuthnGuard, AuthzGuard)]pub struct UsersController { /* ... */ }Reading the principal back
Section titled “Reading the principal back”AuthnGuard attaches the principal to the request before the handler
runs. The handler reads it with Ambient<P> — same primitive as any
other guard-attached context, and the same parameter on every edge: a GraphQL
operation, a WebSocket message and an MCP tool read the principal their
request’s guards verified the same way.
use nest_rs::core::Ambient;use nest_rs::http::Json;
async fn me(&self, auth: Ambient<Claims>) -> Result<Json<User>> { Ok(Json(self.svc.lookup(&auth.sub).await?))}Ambient<Claims> reads the Claims the guard attached, which are ambient
for the rest of the request; a value something else put in the request’s
extensions is never read. Missing the guard means missing the value, and
the framework returns 500 — the access graph would already have failed
the boot if the controller’s import tree did not provide AuthnGuard.
Public routes opt out
Section titled “Public routes opt out”A #[public] route still runs AuthnGuard — but the guard does not
reject. If a credential is present and valid, the principal is
attached so a downstream policy guard can see who is calling. If
nothing is present, or the credential is bad, the request continues
anonymously. Visitor-rule policy belongs in the authorization layer,
not in AuthnGuard.
One failure #[public] does not absorb: AuthError::Unavailable.
An unreachable identity store or identity provider means the credential
was never evaluated, so the request fails closed with a 503 — carrying a
Retry-After when the wait is known: the provider’s own, or for a JWK Set
the time until its next fetch may start — rather than being served as
anonymous: otherwise an outage would silently downgrade every
authenticated caller to a visitor, and a #[public] route’s visitor
rules would decide what they see. A strategy that does not answer within
AUTHENTICATE_TIMEOUT never evaluated the credential either, and gets
the same 503 on every route.
#[get("/health")]#[public]async fn health(&self) -> &'static str { "ok" }Errors
Section titled “Errors”AuthError covers the failure modes a strategy hits:
MissingCredentials, InvalidToken, InvalidSignature,
InvalidAlgorithm, UnknownKey, NotYetValid, Expired,
SenderConstrained, Failed — each
a 401 — plus Unavailable, which is a 503. Failed collapses to a
generic "authentication failed" on the wire so the message never leaks
configuration detail.
Failed and Unavailable are the two your strategy builds itself, and
each keeps what went wrong for the operator. Name the detail — what failed,
never a value the request carried — and hand over the error that caused it
when there is one; the demo’s password login does it when its user store
does not answer:
fn store_unavailable(err: RepoError) -> AuthError { // … AuthError::unavailable_because("the credential store is unreachable", None, err)}The error displays the constant the caller reads — "authentication failed" or "authentication unavailable" — and keeps the detail, then the
cause’s chain, as its source(). The line the edge files for the guard’s
refusal carries that whole chain as its error, through
nest_rs::core::error_message, a decode failure in it said without its
value — and so does every other reader, a {:?} or a main returning it,
which reads the cause as that one sentence — so you never format! an error
into the detail:
authentication unavailable: the credential store is unreachable: <the driver's error>Both variants are built through these constructors — failed,
failed_because, unavailable and unavailable_because — and matched as
AuthError::Failed { .. } and AuthError::Unavailable { .. }. A cause is
logged, never answered, so it must not quote a credential or a value the
request sent either: say a URL through nest_rs::config::endpoint_shown, a
serde failure through nest_rs::core::DecodeError.
Unavailable is the odd one deliberately: it means the identity store or
the identity provider could not be reached, or answered that it cannot
answer now, so the credential was never evaluated. The caller did nothing
wrong (RFC 9110 §15.6.4) — reporting it as a 401 would tell a caller with
a perfectly good token to go get another one, and would let an outage
read as a wave of authentication failures. The edge files it at warn, as
every 503, whether the guard refused with it (reason = "unavailable") or
a handler answered it with ?, and either way it is rendered as a 503
with a Retry-After when retry_after is known — an
identity provider’s own, or for a JWK Set the time until its next fetch may
start, never before what the issuer asked
(JWT) —
given in seconds and rounded up to one at least,
since 0 would tell the caller to retry at once — and none invented when it
is not. The guard answers a strategy that outlived AUTHENTICATE_TIMEOUT
with the same 503, which the edge files at warn under reason = "strategy_timeout". What the refusal says of the identity store stays on the
server: HTTP’s 503 carries no detail, and the GraphQL, MCP and
WebSocket edges, which have no status line, answer "service unavailable" with the class a client branches on — extensions.code: "UNAVAILABLE" on GraphQL, code: "UNAVAILABLE" under data on MCP and
on WebSocket — and, when known, retryAfterSeconds.
A rejected credential also names why on the challenge, per RFC 6750 §3.1:
WWW-Authenticate: Bearer error="invalid_token"A handler answering an AuthError itself with ? adds error_description, the
sentence the caller reads.
A request that carried no credentials is told no reason — §3 says a server “SHOULD NOT include an error code or other error information” there, because an unauthenticated probe has learned nothing yet.
Those challenges are a resource server’s. A token endpoint authenticates a
client, which RFC 6749 §5.2 refuses in its own words — invalid_client,
with a Basic challenge when the client used the Authorization header —
so its route binds ClientAuthenticationGuard over the same Strategy
rather than AuthnGuard
(Token endpoint).
A password-login service that wants to refuse without distinguishing
“wrong email” from “wrong password” returns CredentialError instead
— an opaque "invalid credentials" for any miss. See
Password for the timing-safe
shape of that path.
Pick the strategy that matches
Section titled “Pick the strategy that matches”- JWT — a resource server verifies a signed bearer token. HS256 (shared secret), EdDSA (asymmetric, the resource server holds only the public key), or the JWK Set an external issuer publishes.
- OAuth2 — full authorization-code flow with PKCE, against any provider.
- Password — Argon2id hashing
plus
burn_verifyfor timing-safe rejection. - Split deployment — the deployment pattern that lets a single token signer feed several verify-only APIs.
- Writing a strategy — a credential none of them reads: an API key, a session cookie.
Once the principal is on the request, the authorization layer takes over — see Authorization.
In this section
Section titled “In this section”Basics
Section titled “Basics”- Password — Argon2id hashing, and a miss path whose timing tells the caller nothing.
- JWT — verify a signed bearer token, and hold only the public key on a resource server.
- Signing a token — mint an access token for this app, or for the resource a client asked for.
All options
Section titled “All options”- JWT configuration — the key that picks HS256, EdDSA or a JWK Set, and the issuer and audience.
- OAuth2 — the authorization-code flow with PKCE, and stateless CSRF state.
- OAuth2 client configuration — the client’s fields, its TLS and the bound on every provider call.
- Token endpoint — RFC 6749’s token endpoint, its client authentication and its refusals.
- Split deployment — one signer, many verifiers, no RPC across the boundary.
- Protected resource metadata — the RFC 9728 document telling a client where to get a token.
- Social login — each provider is one module import, active once its credentials are configured, through an open contract.
- Writing a social provider — a provider of your own, published through the same seam.
- External identity provider — accept the tokens better-auth, Keycloak or Auth0 issues, against the JWK Set it publishes.
- Writing a strategy — a
Strategyof your own, for a credential no shipped one reads.
Going further
Section titled “Going further”- Authorization — what the caller may do once identified.
- Add login + protect a route — the same pieces as a recipe, end to end.
- Threat model — what these layers cover, and what they leave to you.