rust
41 lines · 7 steps
An admin route guard in Axum middleware
A middleware that only enforces admin access on /admin routes and passes everything else straight through.
Explained by
highlit
1use axum::{
2 body::Body,
3 extract::MatchedPath,
4 http::{Request, StatusCode},
5 middleware::Next,
6 response::Response,
7};
8
9use crate::auth::CurrentUser;
10
11pub async fn admin_guard(req: Request<Body>, next: Next) -> Result<Response, StatusCode> {
12 let matched = req
13 .extensions()
14 .get::<MatchedPath>()
15 .map(|m| m.as_str().to_owned());
16
17 let requires_admin = matched
18 .as_deref()
19 .map(|path| path.starts_with("/admin"))
20 .unwrap_or(false);
21
22 if !requires_admin {
23 return Ok(next.run(req).await);
24 }
25
26 let user = req
27 .extensions()
28 .get::<CurrentUser>()
29 .ok_or(StatusCode::UNAUTHORIZED)?;
30
31 if !user.is_admin {
32 tracing::warn!(
33 user_id = %user.id,
34 path = matched.as_deref().unwrap_or("<unknown>"),
35 "blocked non-admin access to admin route"
36 );
37 return Err(StatusCode::FORBIDDEN);
38 }
39
40 Ok(next.run(req).await)
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Reading MatchedPath lets middleware branch on the route pattern instead of the raw URL.
- 2Guarding only the paths that need it keeps unrelated requests fast and untouched.
- 3Returning a StatusCode as the error type turns authorization failures into clean HTTP responses.
Related explainers
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/an-admin-route-guard-in-axum-middleware-explained-rust-61a5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.