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?
Asked
Active
Viewed 839 times
4
-
1just make it return a `Result<(), Reject>`? – Netwave Dec 20 '20 at 19:00
-
Can you please include a code example of the function? – ryanwebjackson Dec 20 '20 at 20:26
-
Does this answer your question? [How to check the authorization header using Warp?](https://stackoverflow.com/questions/54988438/how-to-check-the-authorization-header-using-warp) – Pramod Jan 26 '21 at 09:10
1 Answers
3
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.

Netwave
- 40,134
- 6
- 50
- 93
-
Where is the `SharedContext` type coming from? That's application specific, not warp code yes? – Alex Moore-Niemi Jun 08 '21 at 17:12
-
@AlexMoore-Niemi, yes, this came from a functional piece of code. But the shared context is just an `Arc
>` of some struct. – Netwave Jun 09 '21 at 07:47