如何使用 Warp 检查授权标头? [英] How to check the authorization header using Warp?
问题描述
我正在用 Rust 和 Warp 构建一个 graphql api.我已经浏览了文档,但我仍然没有弄清楚如何链接过滤器,尤其是检查请求标头中的 authorization
.
I'm building a graphql api with Rust and Warp. I've looked through the docs, but I have still not figured out how to chain the filters, especially for checking the authorization
in request header.
let context_extractor = warp::any()
// this code rejects all request which doesn't contain the authorization in header
// I'd like to make to check if authorization in header
.and(warp::header::<String>("authorization"))
.map(|token: String| -> Context {
let token_data = match verify_jwt(token) {
Ok(t) => t,
Err(_) => return Context { user_id: 0 },
};
Context {
user_id: token_data.claims.user_id,
}
});
let handle_request = move |context: Context,
request: juniper::http::GraphQLRequest|
-> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(&request.execute(&schema, &context))
};
warp::post2()
.and(warp::path(path.into()))
.and(context_extractor)
.and(warp::body::json())
.map(handle_request)
.map(build_response)
.boxed()
这是我的代码部分.它工作正常,但有一个问题.我已经用 .and(warp::header::<String>("authorization")
设置了一个路由 context_extractor
,然后它拒绝所有不存在的请求t 在标题中包含 authorization
.
This is my part of code. It works fine, but there is one problem. I've set up one route context_extractor
with .and(warp::header::<String>("authorization")
, then it rejects all requests which doesn't contain authorization
in header.
我该怎么做
如果请求头在头中有
authorization
,则返回Context
和正确的user_id
如果不是,返回 Context
和 user_id: 0
?
if not, return Context
with user_id: 0
?
推荐答案
我找到了 解决方案.
这是一个小片段.
let context_extractor = warp::any().and(
warp::header::<String>("authorization")
.map(|token: String| -> Context {
let token_data = match verify_jwt(token) {
Ok(t) => t,
Err(_) => return Context { user_id: 0 },
};
Context {
user_id: token_data.claims.user_id,
}
})
.or(warp::any().map(|| Context { user_id: 0 }))
.unify(),
);
这篇关于如何使用 Warp 检查授权标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!