Skip to content

Calling your API

An app calls your backend with an access token: a short-lived ES256 JWT that says who the user is (sub), which API it is for (aud), and what the user may do there (roles, permissions). Your backend verifies it offline against the environment’s published keys. This page covers both ends.

Every access token has exactly one audience. Which one is decided when the token is issued:

  1. the resource the request named (RFC 8707), if any;
  2. otherwise the client’s default API, set on the client under Clients;
  3. otherwise the built-in account API, which only the account API accepts.

A client may name the account API, any API of its own app, and an API of another app of the group that it was allowed. Anything else is refused with invalid_target. So give each client the default API it calls most, and name the others with resource when you need them.

auth-react’s authFetch sends the token, with a fresh DPoP proof for that request, and refreshes it when it is about to expire:

import { authFetch } from '@seek-services/auth-react'
// the client's default API
const orders = await authFetch('https://api.your-app.com/orders')
// another API: a token for it, kept in memory beside the first
const invoices = await authFetch('https://billing.your-app.com/invoices', { resource: 'billing-api' })

When you need the raw token, useAuthStore.getState().getAccessToken({ resource }) gives it. Tokens of a single-page app are bound to a key that never leaves the browser (DPoP), so they are sent as Authorization: DPoP <token> together with a DPoP proof, and a copied token is of no use without that key. authFetch does both; that is why it is the way to call an API from the browser.

Getting a token for another API uses the refresh token, which rotates. The SDK runs one refresh at a time across tabs, so this is safe to call freely. A refusal is an AuthError with error invalid_target (the client may not name that API) or access_denied (the app that owns it does not let this user in).

A web client keeps the tokens on the server. A handler that needs to call an API as the user asks WebClient for a token for that audience:

use auth_client::web::{WebClient, WebError};
use axum::{extract::State, http::HeaderMap};
async fn invoices(State(web): State<WebClient>, headers: HeaderMap) -> Result<String, WebError> {
let token = web.access_token_for(&headers, "billing-api").await?;
let body = reqwest::Client::new()
.get("https://billing.your-app.com/invoices")
.bearer_auth(&token)
.send()
.await?
.text()
.await?;
Ok(body)
}

The token is minted from the session’s refresh token under a lock and returned, not stored. A refusal comes back as WebError::Refused(code) and leaves the session as it was. Tokens of a web client are not DPoP-bound: send them as Authorization: Bearer.

Apps of one group share their users but not their APIs. For a client of one app to get tokens for an API of another, allow it on the client’s page under Clients, or with the management API (adding takes the admin role, removing does not):

PUT/v1/environments/:id/clients/:client/apisadmin to add
{ "api_ids": ["<billing-api id>"] }

Such a token is still subject to the other app’s rules: if that app does not let the user in, or needs an email address the user has not given, the token is refused with access_denied. Its roles are the user’s group-wide roles and their roles of the app that owns the API.

auth-client does the whole check, DPoP proofs included, in an axum extractor. Make the AuthClient reachable from your router’s state and take AuthUser in a handler:

use auth_client::{AuthClient, AuthError, AuthUser};
use axum::{extract::FromRef, routing::post, 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) -> Result<String, AuthError> {
user.require_permission("orders:write")?;
Ok(format!("order for {}", user.id()))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
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 });
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app).await?;
Ok(())
}

What AuthUser checks: the header’s typ is at+jwt, the signature is by a key of the environment (the algorithm pinned by the key), iss is the issuer, aud is your audience, exp has not passed (30 seconds of leeway), and, for a DPoP-bound token, the proof. A refusal answers 401 with { "code", "message" } and a WWW-Authenticate header; require_permission and require_role answer 403 insufficient_permission.

The URL a DPoP proof is checked against is the base URL set with with_base_url, or https:// and the request’s Host header without it, followed by the path the handler’s router sees. Set with_base_url behind a proxy, and register DPoP-protected routes at their full path: inside axum’s Router::nest a handler sees the path without the prefix, which does not match the proof.

Nothing ties your API to the SDK. With any JWT library:

  1. Fetch the keys from the jwks_uri of the discovery document, https://your-app.auth.dev.seek.services/jwks.json, and cache them; pick the key by the token’s kid, and fetch again when a kid is unknown (keys rotate, see Keys and secrets).
  2. Require the header’s typ to be at+jwt. This is what tells an access token from an ID token, which is signed by the same keys; never accept an ID token as an access token.
  3. Require alg ES256. Access tokens are always ES256.
  4. Check iss equals the issuer exactly, aud equals your API’s audience (a single string), and exp is in the future.
  5. If the token has a cnf.jkt claim it is DPoP-bound: accept it only with the scheme DPoP and a valid proof whose key thumbprint is cnf.jkt. A bound token sent as Bearer is a stolen token. See DPoP.
  6. Read sub, roles, permissions, acr and scope from the verified claims.

The token’s sub is the user’s id, stable within one environment. When a backend needs more (the email address, the name), it asks the issuer rather than taking it from the caller:

let profile = auth.userinfo(&token).await?; // serde_json::Value: sub, email, name, ...

/userinfo answers only for a token granted the openid scope, from a session that is still active. A DPoP-bound token from a browser cannot be sent there by your backend, since the proof has to come from the browser’s key; and a machine client’s token has no user. For those, use sub, or keep the profile your app stored when the user first arrived. See /userinfo.

An access token cannot be taken back: once issued it is valid until it expires, five minutes by default. A confidential client (one with a secret) that must know sooner can introspect a token that was issued to it, or one for its own default API: the answer is "active": true only while the session the token came from is still good. Machine clients’ tokens always introspect as inactive, since they have no session.