Web app with a backend
In this quickstart the tokens never reach the browser. Your backend is a confidential web client: it logs the user in, keeps their tokens in your database, refreshes them, and gives the browser only an HttpOnly cookie. The page uses the same auth-react login, pointed at your backend.
Before you start
Section titled “Before you start”- An app in the dashboard, and a Postgres-protocol database for your backend (it is used with CockroachDB).
WebClientcreates three tables in it,app_sessions,app_loginsandapp_refresh_intents. - In Clients of the development environment, create a client of type Web. Development accepts
http://localhostpages; in production, list your page’s origin under Allowed origins and its callback address under Redirect URIs (adding addresses takes the admin role). The client secret is shown once.
1. Add the crate with the web feature
Section titled “1. Add the crate with the web feature”[dependencies]auth-client = { path = "../auth/crates/auth-client", features = ["web"] }axum = "0.7"serde_json = "1"sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres"] }tokio = { version = "1", features = ["full"] }See Installing.
2. Mount the routes
Section titled “2. Mount the 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"], "acr": user.claims.acr, }))}
#[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 client_id = std::env::var("AUTH_CLIENT_ID")?; let client_secret = std::env::var("AUTH_CLIENT_SECRET")?; let database_url = std::env::var("DATABASE_URL")?;
// The audience of the session's tokens: `account` unless the client has a default API. let auth = AuthClient::discover(&issuer, "account").await?; let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(5) .connect(&database_url) .await?; // Creates its tables and indexes if they are missing. 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 });
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?; axum::serve(listener, app).await?; Ok(())}web.router() serves /auth/start, /auth/callback, /auth/session, /auth/logout, /auth/session-ticket and /auth/account/*. SessionUser is the signed-in user of a request (from its cookie), or 401 not_logged_in.
3. Point the page at your backend
Section titled “3. Point the page at your backend”The page uses auth-react (npm install @seek-services/auth-react). Serve it from the same origin as the backend, and give <AuthProvider> the path of the routes:
import { createRoot } from 'react-dom/client'import { AuthProvider, useAuthStore } from '@seek-services/auth-react'
createRoot(document.getElementById('root')!).render( <AuthProvider issuer='https://your-app.auth.dev.seek.services' clientId='your-app-web' backend='/auth'> <Header /> </AuthProvider>,)
function Header() { const { user, login, logout } = useAuthStore() return user ? <button onClick={logout}>Log out</button> : <button onClick={login}>Log in</button>}The login is the same dialog as in a single-page app. What happens:
login()asksPOST /auth/start, which makes the PKCE pair, keeps the verifier, and sets a 15-minute login cookie.- The dialog runs the login steps with the issuer and gets an authorization code.
POST /auth/callbackhands the code to your backend, which exchanges it with the client secret, stores the tokens inapp_sessions, and sets the session cookie,__Host-session(HttpOnly,Secure,SameSite=Lax).- On every page load the provider asks
GET /auth/sessionwho is signed in.
Your own routes read the user with SessionUser. On the page, authFetch from auth-react is a plain fetch with the cookie for a web client, so authFetch('/api/me') reaches me above.
4. Call another API from the backend
Section titled “4. Call another API from the backend”The session’s tokens are for one audience. For another API, ask the session for a token on the spot:
use axum::http::HeaderMap;
async fn orders(axum::extract::State(state): axum::extract::State<AppState>, headers: HeaderMap) -> Result<String, auth_client::web::WebError> { let token = state.web.access_token_for(&headers, "orders-api").await?; // call the orders API with `Authorization: Bearer {token}` Ok(token.len().to_string())}An API the client may not name answers WebError::Refused("invalid_target"), and the session stays as it was.
How long the session lasts
Section titled “How long the session lasts”The backend refreshes the tokens when the access token has under 30 seconds left, one request at a time per session, so a refresh token is never used twice. The app’s session lasts as long as the refresh token would rest unused (30 days out of the box) and moves on with each renewal; it ends when the service refuses a refresh with invalid_grant, when the user logs out, or when you end it with end_sessions_of(user_id), for example from a webhook about a deleted user. Remove app_sessions rows whose expires_at has passed on a schedule of your own.
Settings and other apps
Section titled “Settings and other apps”- The account settings components (
<Passkeys />,<TwoStep />,<LinkedAccounts />) work the same, through/auth/account/*. See Account settings. /auth/session-ticketsigns the user in at another app of the group. See Apps that share accounts.- Pages served from another origin than the backend need
.with_page_origin("https://app.your-app.com")and a CORS policy that lets them read the answers. - Two apps on one developer’s
localhostneed a cookie name each:.with_cookie_name("__Host-shop").
See the WebClient reference.