Skip to main content

require_auth

Function require_auth 

Source
pub async fn require_auth(
    request: Request<Body>,
    next: Next,
) -> Result<Response, StatusCode>
Expand description

Axum middleware layer that enforces Bearer token auth on every request except public paths.

ยงExamples

use axum::{
    Router,
    body::Body,
    http::{Request, StatusCode},
    middleware,
    routing::get,
};
use codetether_agent::server::auth::{AuthState, require_auth};
use tower::ServiceExt;

let app = Router::new()
    .route("/secure", get(|| async { "ok" }))
    .layer(middleware::from_fn(require_auth))
    .layer(axum::Extension(AuthState::with_token("example-token")));

let response = app
    .oneshot(
        Request::builder()
            .uri("/secure")
            .header("authorization", "Bearer example-token")
            .body(Body::empty())
            .expect("request"),
    )
    .await
    .expect("response");

assert_eq!(response.status(), StatusCode::OK);