Skip to content

OAuth2

Authorization-code flow with PKCE — OAuthClient builds the redirect, validates the callback, and the JWT carries the CSRF state stateless.

OAuthClient runs the authorization-code flow against any provider that speaks RFC 6749. The flow uses PKCE end-to-end and keeps the CSRF state in a signed cookie — no server-side session, no Redis lookup, no in-memory map. The redirect leg answers the 302 the browser follows; the callback leg validates the state, exchanges the code for an access token, and hands you the provider’s user info.

The implementation wraps the oauth2 crate, configured against the provider via OAuthClientConfig. Profile mapping stays in your app’s Strategy so the client itself never sees your principal type.

The OAuth 2.0 client role — this app obtaining a token from somebody else’s authorization server — is its own capability. RFC 6749 §1.1 names four roles, and the crate that answers who the caller is is a different one.

Terminal window
cargo add nest-rs --features oauth-client

Enabling social brings it along: every social provider composes this client as its shared flow.

An app issuing tokens of its own also plays §1.1’s authorization server, a capability of its own: /callback below answers with its AccessTokenResponse, and Token endpoint is that endpoint whole, so nest_rs::oauth::server needs its feature beside this one.

Terminal window
cargo add nest-rs --features oauth-server

OAuthClientModule registers an OAuthClient as global infrastructure, configured via <PREFIX>_OAUTH__CLIENT__* env vars. Pin the config in code by passing an OAuthClientConfig.

apps/auth/src/module.rs
#[module(
imports = [
OAuthClientModule,
AuthnHttpModule,
],
)]
pub struct AuthModule;

A controller then exposes the two HTTP legs. Behind a social provider, the callback’s strategy is the framework’s (Social login, the exemplar in crates/features/src/sign_in/); over a client of your own it looks like this:

crates/features/src/authn/http/controller.rs
use std::sync::Arc;
use nest_rs::authn::JwtService;
use nest_rs::core::Ambient;
use nest_rs::http::{Result, controller, routes};
use nest_rs::oauth::client::{AuthorizationRedirect, OAuthClient};
use nest_rs::oauth::server::AccessTokenResponse;
#[controller(path = "/")]
pub struct OAuthController {
#[inject]
client: Arc<OAuthClient>,
#[inject]
jwt: Arc<JwtService>,
#[inject]
issuer: Arc<TokenIssuer>,
}
#[routes]
impl OAuthController {
#[get("/authorize")]
#[public]
async fn authorize(&self) -> Result<AuthorizationRedirect> {
Ok(self.client.authorize(&self.jwt, "github", None)?)
}
// NOT `#[public]`: `OAuthGuard` authenticates *from* `code`/`state`, so it
// must be allowed to reject. A forged callback is then the documented
// `401`; marked public, the guard would absorb the denial and the handler
// would fail on the missing principal instead.
#[get("/callback")]
#[use_guards(OAuthGuard)]
async fn callback(&self, caller: Ambient<Caller>) -> Result<AccessTokenResponse> {
Ok(self
.issuer
.issue(caller.user_id, caller.org_id, caller.roles.clone())?)
}
}

Only /authorize is #[public]: it runs before any credential exists, and it binds no guard because there is nothing yet to authenticate. /callback is the opposite — code and state are the credential, and OAuthGuard (your app’s Strategy<Principal = Caller>) is what verifies them. Marking it #[public] tells AuthnGuard to admit a rejected credential as anonymous, which turns a forged-callback 401 into a failure on the missing principal — invisible to any alert, WAF rule or rate limit keyed on 401.

/authorize returns what the client answers, an AuthorizationRedirect: the 302 to the provider, the transaction cookie and Cache-Control: no-store are the framework’s, and the OpenAPI document names the 302 and its Location off the return type.

/callback returns AccessTokenResponse bare. The type renders its own JSON with the Cache-Control: no-store and Pragma: no-cache RFC 6749 §5.1 requires on a token, so the browser that followed the redirect keeps no copy of it in a back-forward cache, and the OpenAPI document reads the body off the return type all the same.

Every OAuthClientConfig field, the TLS each call to the provider runs over, and the bound each call is held to are on OAuth2 client configuration.

authorize produces the answer a handler returns: the URL the browser follows and the signed transaction cookie that ties the round-trip together.

crates/features/src/authn/http/controller.rs
Ok(self.client.authorize(&self.jwt, "github", Some("https://api.example.com"))?)

The provider argument is the registry key of the provider this flow is for. It is load-bearing: it is minted into the transaction, and callback refuses a transaction issued for a different provider (AuthError::Failed, its detail OAuth provider mismatch) before the CSRF compare — which is what stops a transaction being replayed across providers. The resource is the RFC 8707 resource your own token is asked for once the flow ends, signed into the transaction so the callback reads back what the redirect leg asked (None when it named none).

The transaction is a JSON Web Token signed by your app’s JwtService, carrying the random CSRF state, the PKCE verifier, the resource and exp. The browser stores it as a cookie the framework names and writes, and the callback leg verifies the signature before trusting any of it.

The framework generates a fresh PKCE pair per flow (PkceCodeChallenge::new_random_sha256) and a fresh CSRF token (CsrfToken::new_random) — never reuse across requests.

The provider redirects to redirect_url with state and code query parameters — or, when it refuses, state and §4.1.2.1’s error. OAuthClient::transaction_from reads the transaction back from the request’s Cookie fields — every one of them, since HTTP/2 may split the cookies over several — by its exact name. callback takes the query as the request carries it: it verifies the cookie’s signature, checks it belongs to the provider and compares its CSRF state to the query’s in constant time before it reads anything else there, then answers the provider’s refusal or the matched AuthorizationResponse — the only value exchange trades for a TokenSet:

crates/features/src/authn/http/controller.rs
let transaction_cookie = OAuthClient::transaction_from(
req.headers()
.get_all(header::COOKIE)
.iter()
.filter_map(|field| field.to_str().ok()),
)
.ok_or_else(|| AuthError::failed("OAuth transaction cookie missing"))?;
let response = OAuthClient::callback(
&self.jwt,
"github", // the same provider the transaction was minted for
transaction_cookie,
req.uri().query().unwrap_or_default(),
)?;
let resource = response.resource().map(str::to_owned);
let tokens = self.client.exchange(response).await?;

TokenSet carries the access_token, and a refresh_token when the provider returns one. id_token stays None here: an OIDC provider overrides SocialProvider::exchange to fill it, so it can read identity from the id_token rather than a userinfo call.

The CSRF check runs before the exchange — never the other way around: no exchange takes a response nobody matched. A mismatched state returns AuthError::Failed, its detail OAuth state mismatch, and the flow stops.

userinfo<T> fetches the provider’s profile endpoint with the access token as a bearer and deserializes the body into your app’s provider-specific shape:

crates/features/src/authn/http/controller.rs
#[derive(Debug, Deserialize)]
struct GoogleUser {
sub: String,
email: String,
name: String,
}
let profile: GoogleUser = self.client.userinfo(tokens.access_token.expose_secret()).await?;

Mapping the provider profile into your principal (looking the user up in your DB, creating one if absent, issuing your app’s JWT) is the Strategy’s job — OAuthClient deliberately never sees your principal type.

AuthorizationRedirect — the redirect leg’s return value

Section titled “AuthorizationRedirect — the redirect leg’s return value”
nest_rs::oauth::client::AuthorizationRedirect
pub struct AuthorizationRedirect { /* private fields */ }
impl AuthorizationRedirect {
pub fn url(&self) -> &str;
}

A handler returns it, bare or inside a Result, and RFC 6749 §4.1.1’s redirect is written for it:

HTTP/1.1 302 Found
location: <url>
set-cookie: __Host-oauth_tx=<token>; Path=/; Max-Age=600; HttpOnly; Secure; SameSite=Lax
cache-control: no-store

no-store means no cache keeps the response that set the cookie, and the answer is the cookie’s one way out: its fields are private and written valid where authorize builds them, so a handler cannot set it on a response of its own. url() reads where the browser is sent. A transaction jwt cannot sign — a verify-only service — is a SignError, the opaque 500 with no cookie, no challenge and its chain at error.

Behind a social provider, SocialRegistry::authorize answers a SocialRedirect wrapping this one, or the 404 for a provider no imported module registers (Social login).

The cookie’s name is OAuthClient::TRANSACTION_COOKIE, the framework’s rather than yours. Its __Host- prefix makes a browser refuse it unless it is Secure, on Path=/ and without a Domain, so a sibling subdomain can neither plant nor overwrite it. HttpOnly keeps it from every script. SameSite=Lax lets it ride the provider’s redirect back, a top-level cross-site navigation that Strict would strip.

The transaction lives OAuthClient::TRANSACTION_TTL_SECS — ten minutes, the signed token’s exp and the cookie’s Max-Age alike — whatever your JwtService’s expires_in. A user who takes longer to consent starts the flow again.

  • Social login — mount GitHub/Google (or your own provider) over this client through an open, discovered provider contract.
  • OAuth2 client configuration — the fields, the TLS and the bound on every provider call.
  • JWT — the access token your callback issues.
  • Threat model — what PKCE + CSRF cookies catch, and what they don’t.