Available on crate feature auth only.
Expand description

Authorize requests using ValidateRequest.

Example

use tower_http::validate_request::{ValidateRequest, ValidateRequestHeader, ValidateRequestHeaderLayer};
use hyper::{Request, Response, Body, Error};
use http::{StatusCode, header::AUTHORIZATION};
use tower::{Service, ServiceExt, ServiceBuilder, service_fn};

async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
    Ok(Response::new(Body::empty()))
}

let mut service = ServiceBuilder::new()
    // Require the `Authorization` header to be `Bearer passwordlol`
    .layer(ValidateRequestHeaderLayer::bearer("passwordlol"))
    .service_fn(handle);

// Requests with the correct token are allowed through
let request = Request::builder()
    .header(AUTHORIZATION, "Bearer passwordlol")
    .body(Body::empty())
    .unwrap();

let response = service
    .ready()
    .await?
    .call(request)
    .await?;

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

// Requests with an invalid token get a `401 Unauthorized` response
let request = Request::builder()
    .body(Body::empty())
    .unwrap();

let response = service
    .ready()
    .await?
    .call(request)
    .await?;

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

Custom validation can be made by implementing ValidateRequest.

Structs

  • Type that performs basic authorization.
  • Type that performs “bearer token” authorization.