get401-axum
get401 authentication for Axum. Provides Axum extractors and Tower middleware layers for JWT verification — choose whichever style fits your architecture.
Backend only. Runs in Tokio-based Axum server applications.
Installation
[]
= "0.1"
= "0.1" # for TokenClaims, Get401Error types
= "0.8"
= { = "1", = ["full"] }
Setup
Create a Get401Auth and add it to your Axum application state:
use ;
use Get401Auth;
let auth = new;
let app = new
.route
.with_state;
Composite app state
When your application state contains more than auth:
use FromRef;
use Get401Auth;
// Required so extractors can find Get401Auth inside AppState
Style 1 — Extractors (per-handler auth)
Best when different routes have different auth requirements.
Claims — require authentication
use ;
use ;
use ;
async
let app = new
.route
.with_state;
OptionalClaims — optional authentication
async
Manual role / scope checks in the handler
use StatusCode;
async
async
Style 2 — Tower Layers (route-group auth)
Best for protecting entire groups of routes without touching individual handlers.
Successful authentication injects TokenClaims as a request extension.
RequireAuthLayer — require valid token
use ;
use TokenClaims;
use ;
// Handler reads claims from the extension injected by the layer
async
let app = new
.route
.route
.route_layer;
RequireRolesLayer — require roles
use RequireRolesLayer;
let app = new
// At least one role
.route
.route_layer
// All roles required
.route
.route_layer;
RequireScopeLayer — require a scope
use RequireScopeLayer;
let app = new
.route
.route_layer;
AuthLayer — soft population (never rejects)
Populates Option<TokenClaims> as an extension on every request.
Useful as a global layer when you want claims available everywhere but don't
want to block unauthenticated requests at the middleware level.
use Extension;
use TokenClaims;
use AuthLayer;
async
let app = new
.route
.layer;
Mixing both styles
You can freely combine extractors and layers in the same application:
// route_layer wraps every route on the same Router — always isolate
// layer-protected routes in a sub-router and merge them in.
let protected = new
.route
.route
.route_layer;
let app = new
.route // OptionalClaims — no layer needed
.merge
.with_state;
HTTP responses on failure
| Situation | Status |
|---|---|
Missing aact cookie |
401 Unauthorized |
| Expired token | 401 Unauthorized |
| Invalid / tampered token | 401 Unauthorized |
| Wrong algorithm | 401 Unauthorized |
| Missing role | 403 Forbidden |
| Missing scope | 403 Forbidden |
| get401 backend unreachable | 503 Service Unavailable |
All error bodies are JSON: {"error": "<message>"}.
Full example
use ;
use TokenClaims;
use ;
use ;
use TcpListener;
async
async
async
async
async
async