Protect a route
Add Auth::layer to the routes, and an extractor to the handler. The state of the application can be anything.
use std::sync::Arc;
use auth_chad::axum::{Auth, FirstParty, Refused};
use auth_chad::sqlite::SqliteStore;
use axum::Router;
use axum::routing::get;
async fn notes(who: FirstParty) -> Result<String, Refused> {
let user = who.user()?; // a UserId; a machine gives `forbidden`
Ok(format!("notes of {user}"))
}
async fn home(who: Option<FirstParty>) -> &'static str {
if who.is_some() { "welcome back" } else { "hello" }
}
fn app(auth: &Arc<Auth<SqliteStore>>) -> Router {
let routes = Router::new().route("/notes", get(notes)).route("/", get(home));
auth.layer(routes).merge(auth.router())
}
Your own extractor builds on it, for example for a user’s role:
use auth_chad::axum::{Caller, Refused};
use axum::extract::FromRequestParts;
use axum::http::request::Parts;
struct Admin(auth_chad::UserId);
impl<S: Sync> FromRequestParts<S> for Admin {
type Rejection = Refused;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Refused> {
let user = Caller::of(parts)?.first_party()?.user()?;
// Ask your database: is this user an admin?
Ok(Self(user))
}
}
- Cookies and DPoP both work. A
POSTwith a cookie must come from a page inConfig.origins. - The layer runs once per request and refuses nothing. Without it, the extractors answer 503 to everyone.
- Other middleware can read
Caller, for example to log who did what. It must be inside the layer. - May this user do this? That is the application’s decision. The library says who it is.