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.
Before you start
Section titled “Before you start”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.
1. Add the crate
Section titled “1. Add the crate”[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.
2. Verify tokens with the extractor
Section titled “2. Verify tokens with the extractor”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::discoverread the issuer’s discovery document and keys at start. Keys it does not know yet are fetched again when a token names one.- The
AuthUserextractor takes the token fromAuthorization, checks it is an access token (typat+jwt) signed by the environment fororders-api(aud), and not expired. - A token bound to a browser’s key must come as
Authorization: DPoP <token>with aDPoPproof for this method and URL. The URL isPUBLIC_URLfollowed by the path, so set it to the origin your callers use. The same bound token sent asBeareris refused: it is a copied token. require_permissionanswers403 insufficient_permissionwhen 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 |
3. Call it
Section titled “3. Call it”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:
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.
More checks
Section titled “More checks”| 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.
With any JWT library
Section titled “With any JWT library”Any stack can verify the same tokens. For each request:
- Fetch
{issuer}/.well-known/openid-configurationonce, and the key set at itsjwks_uri({issuer}/jwks.json). Cache the keys, and fetch again when a token names akidyou do not have. - Check the header:
typisat+jwt,algisES256, andkidnames a key of the set. - Check the signature,
iss(exactly the issuer),aud(exactly your API’s audience: it is one string), andexp. - If the token has
cnf.jkt, it is DPoP-bound: require theDPoPscheme and verify the proof (RFC 9449): itsjwkthumbprint equalscnf.jkt,htmandhtumatch the request,iatis recent,athis the hash of the token, and itsjtiwas not seen before. See DPoP. - Authorize from
permissions(this API’s only) androles.
The claims are listed in Tokens and claims.