This is supported on crate feature auth only.
Expand description

Authorize requests using the Authorization header asynchronously.

Example

use tower_http::auth::{AsyncRequireAuthorizationLayer, AsyncAuthorizeRequest};
use hyper::{Request, Response, Body, Error};
use http::{StatusCode, header::AUTHORIZATION};
use tower::{Service, ServiceExt, ServiceBuilder, service_fn};
use futures_util::future::BoxFuture;

#[derive(Clone, Copy)]
struct MyAuth;

impl AsyncAuthorizeRequest for MyAuth {
    type Output = UserId;
    type Future = BoxFuture<'static, Option<UserId>>;
    type ResponseBody = Body;

    fn authorize<B>(&mut self, request: &Request<B>) -> Self::Future {
        Box::pin(async {
            // ...
        })
    }

    fn on_authorized<B>(&mut self, request: &mut Request<B>, user_id: UserId) {
        // Set `user_id` as a request extension so it can be accessed by other
        // services down the stack.
        request.extensions_mut().insert(user_id);
    }

    fn unauthorized_response<B>(&mut self, request: &Request<B>) -> Response<Body> {
        Response::builder()
            .status(StatusCode::UNAUTHORIZED)
            .body(Body::empty())
            .unwrap()
    }
}

#[derive(Debug)]
struct UserId(String);

async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
    // Access the `UserId` that was set in `on_authorized`. If `handle` gets called the
    // request was authorized and `UserId` will be present.
    let user_id = request
        .extensions()
        .get::<UserId>()
        .expect("UserId will be there if request was authorized");

    println!("request from {:?}", user_id);

    Ok(Response::new(Body::empty()))
}

let service = ServiceBuilder::new()
    // Authorize requests using `MyAuth`
    .layer(AsyncRequireAuthorizationLayer::new(MyAuth))
    .service_fn(handle);

Structs

Middleware that authorizes all requests using the Authorization header.

Layer that applies AsyncRequireAuthorization which authorizes all requests using the Authorization header.

Traits

Trait for authorizing requests.