expression

Axum: authentication challenge

Authentication establishes identity. An unauthenticated request to a protected endpoint can receive 401 with an applicable challenge. This endpoint always refuses access; it does not validate any credentials. In-memory standalone Cargo example. Expected stdout (not executed): 401 Bearer realm="demo" Common mistake: Returning 401 without the applicable authentication challenge.

Formal Syntax & Structure

rust syntaxrust
(StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, challenge)])

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::{routing::get, http::header};    let app = Router::new().route("/private", get(|| async {        (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer realm=\"demo\"")])    }));    let r = app.oneshot(Request::builder().uri("/private").body(Body::empty()).unwrap()).await.unwrap();    println!("{}", r.status().as_u16());    println!("{}", r.headers()[header::WWW_AUTHENTICATE].to_str().unwrap());}
Rust Reference