Module require_authorization

Source
Available on crate feature auth only.
Expand description

Authorize requests using ValidateRequest.

§Example

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

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::<Bytes>::default())
    .unwrap();

let response = service

    .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::<Bytes>::default())
    .unwrap();

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

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

Custom validation can be made by implementing ValidateRequest.

Structs§

Basic
Type that performs basic authorization.
Bearer
Type that performs “bearer token” authorization.