expression
Axum: role-based authorization
Authorization decides whether a verified identity may perform an action. This synthetic test distinguishes lack of authentication from a verified identity that lacks permission. Real roles must originate from a trusted policy source. In-memory standalone Cargo example. Expected stdout (not executed): 401 403 200 Common mistake: Assuming every authenticated user has every permission.
Formal Syntax & Structure
rust syntaxrust
match verified_principal.role { ... }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)] enum Role { Reader, Editor } async fn edit(role: Option<Extension<Role>>) -> Response { match role { Some(Extension(Role::Editor)) => StatusCode::OK.into_response(), Some(Extension(Role::Reader)) => StatusCode::FORBIDDEN.into_response(), None => (StatusCode::UNAUTHORIZED, [(header::WWW_AUTHENTICATE, "Bearer")]).into_response(), } } let app = Router::new().route("/", get(edit)); for role in [None, Some(Role::Reader), Some(Role::Editor)] { let mut req = Request::new(Body::empty()); if let Some(role) = role { req.extensions_mut().insert(role); } let r = app.clone().oneshot(req).await.unwrap(); println!("{}", r.status().as_u16()); }}