diff --git a/examples/key_value_store.rs b/examples/key_value_store.rs index 2f2a02ca..d625d864 100644 --- a/examples/key_value_store.rs +++ b/examples/key_value_store.rs @@ -7,8 +7,7 @@ //! ``` use axum::{ - async_trait, - extract::{extractor_middleware, ContentLengthLimit, Extension, Path, RequestParts}, + extract::{ContentLengthLimit, Extension, Path}, prelude::*, response::IntoResponse, routing::BoxRoute, @@ -25,7 +24,8 @@ use std::{ }; use tower::{BoxError, ServiceBuilder}; use tower_http::{ - add_extension::AddExtensionLayer, compression::CompressionLayer, trace::TraceLayer, + add_extension::AddExtensionLayer, auth::RequireAuthorizationLayer, + compression::CompressionLayer, trace::TraceLayer, }; #[tokio::main] @@ -118,41 +118,11 @@ fn admin_routes() -> BoxRoute { route("/keys", delete(delete_all_keys)) .route("/key/:key", delete(remove_key)) - // Require beare auth for all admin routes - .layer(extractor_middleware::()) + // Require bearer auth for all admin routes + .layer(RequireAuthorizationLayer::bearer("secret-token")) .boxed() } -/// An extractor that performs authorization. -// TODO: when https://github.com/hyperium/http-body/pull/46 is merged we can use -// `tower_http::auth::RequireAuthorization` instead -struct RequireAuth; - -#[async_trait] -impl extract::FromRequest for RequireAuth -where - B: Send, -{ - type Rejection = StatusCode; - - async fn from_request(req: &mut RequestParts) -> Result { - let auth_header = req - .headers() - .and_then(|headers| headers.get(http::header::AUTHORIZATION)) - .and_then(|value| value.to_str().ok()); - - if let Some(value) = auth_header { - if let Some(token) = value.strip_prefix("Bearer ") { - if token == "secret-token" { - return Ok(Self); - } - } - } - - Err(StatusCode::UNAUTHORIZED) - } -} - fn handle_error(error: BoxError) -> Result { if error.is::() { return Ok((StatusCode::REQUEST_TIMEOUT, Cow::from("request timed out")));