Skip to content

auth-client (Rust)

auth-client is the Rust SDK for backends. It does four things:

Type For
AuthClient and AuthUser An API that receives access tokens: verify the token (and its DPoP proof) and read who is calling.
WebClient A backend that is a web client: it holds the tokens in your database and gives the browser only an HttpOnly cookie.
MachineClient A job or service that gets tokens of its own with client credentials.
webhook::verify Checking the signature of a webhook delivery.
  • axum 0.7. The extractors and routes are axum 0.7 types.
  • reqwest 0.12. AuthClient::discover_with and MachineClient::new_with take a reqwest::Client of that version.
  • Postgres wire protocol, with the web feature. WebClient keeps its sessions through sqlx 0.8 with Postgres; it is used against CockroachDB, and retries a transaction when the database asks it to.
Feature Default Adds
axum yes The AuthUser extractor and IntoResponse for AuthError.
web no WebClient, its routes and session storage (implies axum).
testing no testing::DpopKey, for tests of code that verifies DPoP proofs.

The crate is not on crates.io; see Installing.

Cargo.toml
[dependencies]
auth-client = { path = "../auth/crates/auth-client", features = ["web"] }

Verifies the access tokens of one environment for one API (audience). It is cheap to clone.

pub async fn discover(issuer: &str, audience: &str) -> Result<AuthClient, AuthError>
pub async fn discover_with(http: reqwest::Client, issuer: &str, audience: &str) -> Result<AuthClient, AuthError>
pub fn with_base_url(self, base_url: &str) -> AuthClient
pub fn issuer(&self) -> &str
pub async fn verify_token(&self, token: &str) -> Result<Claims, AuthError>
pub async fn authenticate(&self, method: &str, url: &str, authorization: Option<&str>, dpop_proof: Option<&str>) -> Result<AuthUser, AuthError>
pub async fn userinfo(&self, access_token: &str) -> Result<serde_json::Value, AuthError>
pub async fn verify_id_token(&self, id_token: &str, client_id: &str) -> Result<serde_json::Value, AuthError>
  • discover reads {issuer}/.well-known/openid-configuration (with a 10-second timeout), refuses metadata whose issuer is not exactly the one given, and loads the signing keys before it returns.
  • Keys are kept an hour. A token signed with a key it does not know makes it fetch the keys again, at most once every 30 seconds; while a fetch fails, the keys it has go on being used.
  • verify_token checks that the token is an access token (typ at+jwt), the signature with the key its kid names (ES256 or RS256, the algorithm pinned by the key), iss, aud, and exp with 30 seconds of leeway. It does not check DPoP: authenticate and the extractor do.
  • with_base_url sets your backend’s public origin, such as https://api.your-app.com, which DPoP proofs are checked against. Without it the origin is https:// and the request’s Host header.
  • userinfo asks the issuer who a token belongs to. Use it when a backend is handed a user’s token and needs their profile; not for a DPoP-bound token (only the browser can make its proof) and not for a machine client’s token, which has no user.

The caller of an API route, as an axum extractor. Your router’s state must hand out an AuthClient through FromRef:

use auth_client::{AuthClient, AuthError, AuthUser};
use axum::{extract::FromRef, routing::post, Json, Router};
#[derive(Clone)]
struct AppState {
auth: AuthClient,
}
impl FromRef<AppState> for AuthClient {
fn from_ref(state: &AppState) -> AuthClient {
state.auth.clone()
}
}
async fn create_order(user: AuthUser, Json(order): Json<NewOrder>) -> Result<Json<Order>, AuthError> {
user.require_permission("orders:write")?;
// user.id() is the user's id, or the client id of a machine client
Ok(Json(save(user.id(), order).await))
}
let auth = AuthClient::discover("https://your-app.auth.dev.seek.services", "orders-api")
.await?
.with_base_url("https://api.your-app.com");
let app = Router::new()
.route("/orders", post(create_order))
.with_state(AppState { auth });

The extractor reads Authorization and DPoP, accepts the Bearer and DPoP schemes, and:

  • a token bound to a key (cnf.jkt) must come with the DPoP scheme and a valid proof for this request’s method and URL, made with that key; the same bound token sent as Bearer is refused, because it is a copied token;
  • an unbound token must come with Bearer;
  • every proof is used once; a replayed proof is refused.

The URL a proof is checked against is the base URL (or https:// and Host) followed by the request’s path as the handler sees it. A route inside Router::nest sees the path without the nest’s prefix, so mount routes that take DPoP-bound tokens where the path the browser calls is the path the handler sees.

Method Returns
id() sub: the user’s id, stable within one environment, or a machine client’s client_id.
is_machine() Whether the caller is a machine client (its token has no session).
has_permission(p), has_role(r) bool.
require_permission(p), require_role(r) Err(AuthError::MissingPermission) / MissingRole, which answer 403.
require_aal2() Err(StepUpRequired) unless the login had two steps, which answers 401 and asks for acr_values="aal2".
require_fresh(max_age) Err(StepUpRequired) unless the user proved who they are within max_age seconds.
claims The verified Claims.
Field Type Meaning
iss, aud, client_id, jti String Issuer, the API’s audience, the client the token was issued to, the token’s id.
sub String The user’s id, or a machine client’s id.
sid String The session the token came from; empty for a machine client.
iat, exp, auth_time i64 Issued, expires, and when the user last proved who they are.
scope String The granted scope.
acr String aal1 or aal2; client for a machine client.
amr, roles, permissions Vec<String> How the user logged in; their roles; the permissions of this token’s audience only.
cnf Option<Confirmation> Some({ jkt }) on a DPoP-bound token.

See Tokens and claims.

With the axum feature it is a response: JSON { "code", "message" } with this status and header.

Variant Status code WWW-Authenticate
MissingToken 401 missing_token DPoP, Bearer
InvalidToken(reason) 401 invalid_token Bearer error="invalid_token"
Dpop(DpopError) 401 invalid_dpop_proof DPoP error="invalid_dpop_proof"
StepUpRequired { acr_values, max_age } 401 insufficient_user_authentication Bearer error="insufficient_user_authentication", with acr_values and max_age when set
MissingPermission(p), MissingRole(r) 403 insufficient_permission
Discovery(reason) 500 discovery_failed

A page that gets a 401 with insufficient_user_authentication asks the user for what the header names with auth-react’s stepUp and tries again: see Step-up.

The backend half of a web client (feature web). The browser talks only to your backend; the backend logs the user in with the authorization code flow and PKCE, stores the tokens in your database (app_sessions), refreshes them, and gives the browser an HttpOnly, Secure, SameSite=Lax cookie. On the page, <AuthProvider backend="/auth"> from auth-react talks to these routes.

use auth_client::web::{SessionUser, WebClient};
use auth_client::AuthClient;
use axum::{extract::FromRef, routing::get, Json, Router};
use serde_json::{json, Value};
#[derive(Clone)]
struct AppState {
web: WebClient,
}
impl FromRef<AppState> for WebClient {
fn from_ref(state: &AppState) -> WebClient {
state.web.clone()
}
}
async fn me(user: SessionUser) -> Json<Value> {
Json(json!({ "id": user.id(), "email": user.profile["email"] }))
}
let auth = AuthClient::discover("https://your-app.auth.dev.seek.services", "account").await?;
let pool = sqlx::postgres::PgPoolOptions::new().connect(&database_url).await?;
let web = WebClient::new(auth, pool, &client_id, &client_secret).await?;
let app = Router::new()
.nest("/auth", web.router())
.route("/api/me", get(me))
.with_state(AppState { web });

The AuthClient given to it must be for the audience the session’s tokens are for: account unless the client has a default API.

Function What it does
WebClient::new(auth, pool, client_id, client_secret) For an app that is one client: creates the tables and indexes if they are missing, then builds the client.
WebClient::prepare(&pool) Creates the tables and indexes once at start, for a host that serves many clients from one database.
WebClient::attach(auth, pool, client_id, client_secret) Builds a client without running a statement (after prepare). Every row names the client that wrote it, so a session is found only by its own client.
.with_page_origin(origin) When the pages are served from another origin than the backend: /logout, /session-ticket and /account/* then answer only that Origin. Your CORS policy still has to let the page read the answers.
.with_cookie_name(name) The session cookie’s name; default __Host-session. Two apps on one developer’s localhost need a name each. Keep the __Host- prefix.
.router() The routes below.

Call the with_* builders before router() and before putting the client into your state: a copy made earlier keeps the old settings. The scope asked for is openid profile email offline_access.

Mount them under the path you give <AuthProvider backend>, such as /auth.

Route Request Answer
POST /start Optional { acr_values?, max_age? } What the page needs to start the login (code_challenge, client_id, scope, state), and a 15-minute login cookie.
POST /callback { code, state, redirect_uri? } { user }, and the session cookie. Without the login cookie of the same login: 400 login_expired.
GET /session { user }, or { user: null }.
POST /logout 204, or 200 { end_session_url } when the login came through the hosted page, for the page to go to. The cookie is cleared either way.
POST /session-ticket { client_id } { session_ticket, expires_in }: see Session tickets.
ANY /account/*path The account API as the user, passed through with a token for the account audience.

user is { id, email, emailVerified, name, picture, acr, amr, authTime }. /logout, /session-ticket and /account/* answer only the app’s own page (same origin, or the one origin named with with_page_origin), with 403 cross_origin otherwise, so a page of another origin (a sibling subdomain too) cannot log your users out; /account/* refuses paths with .., ?, #, \, % or an empty segment, takes JSON bodies of up to 64 KiB, and passes on the status and body but not WWW-Authenticate or Retry-After.

SessionUser (extractor) The signed-in user: Derefs to AuthUser (so id(), claims, require_permission work) and has profile, the ID token’s claims. Without a session: 401 not_logged_in.
web.user(&headers) The same, without the extractor.
web.access_token_for(&headers, audience) An access token for another API, from the session’s refresh token. It is kept in memory for this session and login until its own expiry (the environment’s access token lifetime: 5 minutes by default, up to a day), so the next call for the same audience spends nothing. A user revoked or disabled meanwhile is refused at once by an API that checks the session behind each token, and by any other only when the token runs out, as with the app’s own access token, unless the backend ends the session first (end_sessions_of from the user-disabled webhook). A refused audience is WebError::Refused(code) (invalid_target, access_denied) and leaves the session as it is.
web.drop_token_for(&headers, audience) Drops the kept token for that audience: call it when the API refused the token (401). The next access_token_for mints one, and finds out whether the session still lives.
web.session_ticket(&headers, target_client_id) A session ticket for another app of the group. The client’s secret goes with the request, as the service wants for a bearer token.
web.end_sessions_of(user_id) Ends one user’s sessions at this client, such as when a webhook says the user was deleted or disabled.
web.end_all_sessions() Ends every session of this client.

A backend that renders its pages can log in with redirects in routes of its own:

Function Answer
login_redirect(redirect_uri, return_to) 303 to the issuer’s /authorize, with a login cookie. A return_to that is not a path of your host becomes /.
finish_redirect(&headers, code, state, redirect_uri) 303 back to the return_to the login started with, with the session cookie.
logout_redirect(&headers, back) 303 to the issuer’s /logout (or straight to back), clearing the cookie. Choose back yourself; never take it from the request.
  • A request reads its session in one statement and goes on while the access token has more than 30 seconds left. Only spending the refresh token takes a row lock, so parallel requests never present the same refresh token twice, which the service would treat as reuse.
  • The app session lasts as long as its refresh token would rest unused (refresh_expires_in; 30 days where the service does not say), and moves on with each renewal. A refresh ends the app session only when the service answers invalid_grant; any other refusal leaves it.
  • In one process, the requests of a session wait in memory for a single refresh, holding no database connection. At most a quarter of the pool’s connections hold row locks at once.
  • A token for another audience (/auth/account/*, access_token_for) is minted once and kept in memory for as long as it is good. It is kept for that session and login only: a step-up or a new login mints a new one, and a session that ends drops its tokens.
  • Before it presents a refresh token, the client records that it is about to, in app_refresh_intents. If the refresh then ends without new tokens (no answer, a killed process), the next one presents nothing until the service can no longer use the token (502 upstream_error until then). It then asks introspection: a token that was used up ends the app session instead of being presented again, so there is no reuse and no alert. See a refresh that gets no answer.
  • Expired login rows are removed as logins start, and intents a day after they ran out (prepare). Nothing removes expired app_sessions rows; delete rows whose expires_at has passed on a schedule of your own.

A refresh can outlive the request that started it. Stopping the process in the middle of one can leave a session holding a token the service has already used up. When the stop signal comes:

  1. Call auth_client::web::stop_refreshes(). From then on, a request that needs a refresh gets 503 shutting_down with Retry-After: 1, and another process answers its retry.
  2. Stop taking requests, and let those in flight finish.
  3. Call auth_client::web::finish_refreshes(within).await, which waits for the refreshes already presented and says whether they all finished.

Answers JSON { "code", "message" }:

Variant Status, code
NotLoggedIn 401 not_logged_in
LoginExpired 400 login_expired
Refused(code) 400 login_refused
BadRequest(reason) 400 bad_request
CrossOrigin 403 cross_origin
Auth(AuthError) as AuthError
Service { status, code, message } the service’s own answer
Upstream(reqwest::Error) 502 upstream_error
Database(sqlx::Error) 500 internal_error

Gets and keeps an access token for a machine client, with the client credentials grant:

use auth_client::MachineClient;
// The secret comes from your deployment's secrets, never from the source.
let secret = std::env::var("AUTH_CLIENT_SECRET")?;
let me = MachineClient::new("https://your-app.auth.dev.seek.services", "your-app-machine-1a2b3c", &secret, "orders-api");
let token = me.token().await?; // fetched once, reused until a minute before it expires
let orders = http.get("https://api.your-app.com/orders").bearer_auth(&token).send().await?;
Function
MachineClient::new(issuer, client_id, client_secret, audience) Posts to {issuer}/token with HTTP Basic authentication, grant_type=client_credentials and resource=audience.
MachineClient::new_with(http, issuer, client_id, client_secret, audience) The same with your own reqwest::Client.
token() A token good for at least another minute. Callers that ask at the same time wait for one request.

It is not Clone; share it in an Arc. Errors are MachineError::Http(reqwest::Error) or MachineError::Refused { status, error, description }, such as invalid_client for a wrong secret or invalid_target for an API the client may not name.

pub fn verify(secret: &str, id: &str, timestamp: &str, signature: &str, body: &[u8], now_unix: i64) -> bool

Checks a webhook delivery: id, timestamp and signature are the webhook-id, webhook-timestamp and webhook-signature headers, and body is the raw body exactly as it arrived. It is true when one of the signatures in the header is the HMAC-SHA256 of {id}.{timestamp}.{body} under the secret (whsec_…), and the timestamp is within 300 seconds of now_unix.

use auth_client::webhook;
use axum::{body::Bytes, http::{HeaderMap, StatusCode}};
async fn auth_events(headers: HeaderMap, body: Bytes) -> StatusCode {
let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or_default();
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or_default();
let secret = std::env::var("WEBHOOK_SECRET").unwrap_or_default();
if !webhook::verify(&secret, header("webhook-id"), header("webhook-timestamp"), header("webhook-signature"), &body, now) {
return StatusCode::UNAUTHORIZED;
}
// The same webhook-id can arrive more than once: remember the ones handled.
StatusCode::NO_CONTENT
}

auth_client::dpop is the proof verification AuthUser uses, for a framework other than axum: dpop::verify(proof, Expected { method, url, access_token, now }) returns the proof’s jkt, jti and iat, and ReplayCache remembers the proofs a process has seen. With the testing feature, testing::DpopKey makes keys and proofs for your tests: DpopKey::generate(), jkt(), and proof(method, url, iat, access_token).