Skip to content

Protect an API

Your API receives access tokens from browsers, backends and machine clients. It checks each one offline, against the environment’s published keys, and reads who is calling and what they may do. This quickstart uses the Rust SDK; the end of the page says what any other stack must check.

In APIs and roles, create the API: an audience (here orders-api) and its permissions (orders:read, orders:write). Then a role that holds them, and give it to users in Users (or to a machine client). Tokens for orders-api then carry the role in roles and its permissions in permissions.

Cargo.toml
[dependencies]
auth-client = { path = "../auth/crates/auth-client" }
axum = "0.7"
serde_json = "1"
tokio = { version = "1", features = ["full"] }

See Installing: the crate is not on crates.io yet.

src/main.rs
use auth_client::{AuthClient, AuthError, AuthUser};
use axum::{extract::FromRef, routing::get, Json, Router};
use serde_json::{json, Value};
#[derive(Clone)]
struct AppState {
auth: AuthClient,
}
impl FromRef<AppState> for AuthClient {
fn from_ref(state: &AppState) -> AuthClient {
state.auth.clone()
}
}
async fn list_orders(user: AuthUser) -> Result<Json<Value>, AuthError> {
user.require_permission("orders:read")?;
Ok(Json(json!({
"caller": user.id(),
"machine": user.is_machine(),
"roles": user.claims.roles,
"orders": [],
})))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let issuer = std::env::var("AUTH_ISSUER")?; // https://your-app.auth.dev.seek.services
let public_url = std::env::var("PUBLIC_URL")?; // where browsers reach this API
let auth = AuthClient::discover(&issuer, "orders-api")
.await?
.with_base_url(&public_url);
let app = Router::new()
.route("/orders", get(list_orders))
.with_state(AppState { auth });
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app).await?;
Ok(())
}

What happens on each request:

  • AuthClient::discover read the issuer’s discovery document and keys at start. Keys it does not know yet are fetched again when a token names one.
  • The AuthUser extractor takes the token from Authorization, checks it is an access token (typ at+jwt) signed by the environment for orders-api (aud), and not expired.
  • A token bound to a browser’s key must come as Authorization: DPoP <token> with a DPoP proof for this method and URL. The URL is PUBLIC_URL followed by the path, so set it to the origin your callers use. The same bound token sent as Bearer is refused: it is a copied token.
  • require_permission answers 403 insufficient_permission when the token lacks the permission.

What your callers get when something is wrong:

Situation Status Body code
No token 401 (WWW-Authenticate: DPoP, Bearer) missing_token
Not an access token, wrong issuer or audience, expired, bad signature 401 invalid_token
A DPoP-bound token without a valid proof, or sent as Bearer 401 invalid_dpop_proof
Missing permission or role 403 insufficient_permission

From a React app, with auth-react:

const res = await authFetch('https://api.your-app.com/orders', { resource: 'orders-api' })

From a job, with a machine client:

Terminal window
curl https://api.your-app.com/orders -H "Authorization: Bearer $ACCESS_TOKEN"

A machine client’s token has no user: user.is_machine() is true and user.id() is the client’s client_id.

Need Use
A role user.require_role("admin")? or user.has_role("admin")
A login with two steps for this route user.require_aal2()?: a 401 that asks for acr_values="aal2"; the page then opens a step-up and tries again
A recent login user.require_fresh(300)?: the user proved who they are in the last 300 seconds
The user’s profile auth.userinfo(token), for a bearer token handed to your backend (not for a DPoP-bound token)

See the auth-client reference.

Any stack can verify the same tokens. For each request:

  1. Fetch {issuer}/.well-known/openid-configuration once, and the key set at its jwks_uri ({issuer}/jwks.json). Cache the keys, and fetch again when a token names a kid you do not have.
  2. Check the header: typ is at+jwt, alg is ES256, and kid names a key of the set.
  3. Check the signature, iss (exactly the issuer), aud (exactly your API’s audience: it is one string), and exp.
  4. If the token has cnf.jkt, it is DPoP-bound: require the DPoP scheme and verify the proof (RFC 9449): its jwk thumbprint equals cnf.jkt, htm and htu match the request, iat is recent, ath is the hash of the token, and its jti was not seen before. See DPoP.
  5. Authorize from permissions (this API’s only) and roles.

The claims are listed in Tokens and claims.