Verification
axum middleware
An extractor that verifies the bearer token and hands handlers the Claims. The client lives in app state; clones share its JWKS cache.
rustauth.rs
use axum::{
extract::{FromRef, FromRequestParts},
http::{header::AUTHORIZATION, request::Parts, StatusCode},
};
use decane::{Claims, DecaneClient};
#[derive(Clone)]
pub struct AppState {
pub decane: DecaneClient,
}
impl FromRef<AppState> for DecaneClient {
fn from_ref(state: &AppState) -> Self {
state.decane.clone()
}
}
pub struct CurrentUser(pub Claims);
impl<S> FromRequestParts<S> for CurrentUser
where
DecaneClient: FromRef<S>,
S: Send + Sync,
{
type Rejection = StatusCode;
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
let token = parts
.headers
.get(AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.ok_or(StatusCode::UNAUTHORIZED)?;
let decane = DecaneClient::from_ref(state);
match decane.safe_verify_access_token(token).await {
Ok(Some(claims)) => Ok(CurrentUser(claims)),
Ok(None) => Err(StatusCode::UNAUTHORIZED),
Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR), // JWKS unreachable
}
}
}rustmain.rs
use axum::{routing::get, Json, Router};
async fn me(CurrentUser(claims): CurrentUser) -> Json<serde_json::Value> {
Json(serde_json::json!({ "user_id": claims.user_id }))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let decane = DecaneClient::builder().app_id(std::env::var("DECANE_APP_ID")?).build()?;
let app = Router::new().route("/me", get(me)).with_state(AppState { decane });
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app).await?;
Ok(())
}The same shape works in actix-web or any other framework: build the client once, share it, and map Ok(None) to 401 and Err to 500.