expression

Axum: trusted principal context

A principal is identity information produced after credential verification. This test injects a principal into request extensions directly, as a trusted server component would. The fixture never accepts client-supplied identity headers and is not an authentication implementation. In-memory standalone Cargo example. Expected stdout (not executed): 7 401 Common mistake: Treating a principal ID supplied by the browser as a verified identity.

Formal Syntax & Structure

rust syntaxrust
Option<Extension<Principal>>

Working Example

Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() {    use axum::{Extension, routing::get, response::{IntoResponse, Response}, http::header};    #[derive(Clone)] struct Principal(u32);    async fn who(p: Option<Extension<Principal>>) -> Response {        match p {            Some(Extension(p)) => p.0.to_string().into_response(),            None => (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")]).into_response(),        }    }    let app = Router::new().route("/", get(who));    let mut verified = Request::new(Body::empty());    verified.extensions_mut().insert(Principal(7));    let r = app.clone().oneshot(verified).await.unwrap();    println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 32).await.unwrap()).unwrap());    let r = app.oneshot(Request::new(Body::empty())).await.unwrap();    println!("{}", r.status().as_u16());}
Rust Reference