expression

Axum: resource ownership check

Check permissions for the particular resource, not just for the route. Here the owner ID is fixed server-side and the test supplies verified identities; a real service must enforce the policy on loaded resource data and mutations. In-memory standalone Cargo example. Expected stdout (not executed): 200 403 404 Common mistake: Checking login but omitting the resource-level authorization check. This illustrative policy reveals existence; some services deliberately return 404 for both denial and absence.

Formal Syntax & Structure

rust syntaxrust
verified_principal.id == resource.owner_id

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, extract::Path, response::{IntoResponse, Response}, http::header};    #[derive(Clone)] struct Principal(u32);    async fn read(Path(id): Path<u32>, p: Option<Extension<Principal>>) -> Response {        let Some(Extension(p)) = p else { return (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")]).into_response(); };        if id != 9 { return StatusCode::NOT_FOUND.into_response(); }        if p.0 != 7 { return StatusCode::FORBIDDEN.into_response(); }        "allowed".into_response()    }    let app = Router::new().route("/items/{id}", get(read));    for (id, user) in [(9,7), (9,8), (10,7)] {        let mut req = Request::builder().uri(format!("/items/{id}")).body(Body::empty()).unwrap();        req.extensions_mut().insert(Principal(user));        let r = app.clone().oneshot(req).await.unwrap();        println!("{}", r.status().as_u16());    }}
Rust Reference