假设我有一个函数来检查授权 header 是否有效以及身份验证是否正确。如何制作一个扭曲过滤器来丢弃所有带有无效 header 或虚假凭据的请求?
最佳答案
这是一个构建过滤器的函数示例,该过滤器完全执行此操作:
/// 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()
}
在哪里:API_TOKEN_HEADER
是您要检查的标题。authorize_token
是一个带签名的函数async fn authorize_token(token: String, context: SharedContext) -> Result<(), Rejection>
这实际上计算了身份验证。
关于Rust (warp) 如何丢弃未经授权的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65383671/