Available on crate feature auth only.
Expand description

Authorize requests using ValidateRequest.

§Example

use tower_http::validate_request::{ValidateRequest, ValidateRequestHeader, ValidateRequestHeaderLayer};
use http::{Request, Response, StatusCode, header::AUTHORIZATION};
use tower::{Service, ServiceExt, ServiceBuilder, service_fn, BoxError};
use bytes::Bytes;
use http_body_util::Full;

async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, BoxError> {
    Ok(Response::new(Full::default()))
}

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(Full::default())
    .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(Full::default())
    .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.