expression

Axum: protect a route group

Apply a guard to an explicitly defined group of protected routes. The gate checks trusted test context, not credentials from the client. A real verification layer must establish the principal before this guard. In-memory standalone Cargo example. Expected stdout (not executed): 200 401 200 404 Common mistake: Adding protected routes outside the guarded group without reviewing coverage.

Formal Syntax & Structure

rust syntaxrust
protected.route_layer(gate); public.merge(protected)

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, middleware::{self, Next}, response::{IntoResponse, Response}, http::header};    #[derive(Clone)] struct Verified;    async fn gate(req: axum::extract::Request, next: Next) -> Response {        if req.extensions().get::<Verified>().is_none() {            return (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")]).into_response();        }        next.run(req).await    }    let protected = Router::new().route("/private", get(|| async { "private" })).route_layer(middleware::from_fn(gate));    let app = Router::new().route("/health", get(|| async { "ok" })).merge(protected);    for (path, verified) in [("/health",false), ("/private",false), ("/private",true), ("/missing",false)] {        let mut req = Request::builder().uri(path).body(Body::empty()).unwrap();        if verified { req.extensions_mut().insert(Verified); }        let r = app.clone().oneshot(req).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference