我正在使用 Rust 和 Warp 构建一个 graphql api。我已经查看了文档,但我仍然没有弄清楚如何链接过滤器,尤其是检查 authorization
在请求 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()
这是我的代码部分。它工作正常,但有一个问题。我设置了一条路线 context_extractor
与 .and(warp::header::<String>("authorization")
, 然后它拒绝所有不包含 authorization
的请求在标题中。
我该怎么做
如果请求头有
authorization
在标题中,然后返回Context
使用适当的user_id
如果不是,返回
Context
与user_id: 0
?
最佳答案
我找到了 solution在 Warp 的 github 问题中。
这是一个小片段。
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(),
);
关于rust - 如何使用 Warp 检查授权 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54988438/