rama::http::layer::auth

Module require_authorization

Expand description

Authorize requests using ValidateRequest.

§Example

use bytes::Bytes;

use rama_http::layer::validate_request::{ValidateRequest, ValidateRequestHeader, ValidateRequestHeaderLayer};
use rama_http::{Body, Request, Response, StatusCode, header::AUTHORIZATION};
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};
use rama_core::error::BoxError;

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

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

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

let response = service
    .serve(Context::default(), request)
    .await?;

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

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

let response = service
    .serve(Context::default(), request)
    .await?;

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

Custom validation can be made by implementing ValidateRequest.

Structs§