Let's say I have a function that checks if an authorization header is valid and if the authentication is correct. How do I make a warp filter that discards all requests with invalid header or false credentials?
Let's say I have a function that checks if an authorization header is valid and if the authentication is correct. How do I make a warp filter that discards all requests with invalid header or false credentials?
This is an example of a function that builds a filter that does exactly that:
/// A warp filter that checks the authorization through API tokens.
/// The header `API_TOKEN_HEADER` should be present and valid otherwise the request is rejected.
pub async fn api_token_filter(
context: SharedContext,
) -> impl Filter<Extract = (), Error = Rejection> + Clone {
let with_context = warp::any().map(move || context.clone());
warp::header::header(API_TOKEN_HEADER)
.and(with_context)
.and_then(authorize_token)
.and(warp::any())
.untuple_one()
}
Where:
API_TOKEN_HEADER is the header you want to check.
authorize_token is a function with signature
async fn authorize_token(token: String, context: SharedContext) -> Result<(), Rejection>
That actually computes the authentication.