我正在使用 Rust 和 Warp 构建 graphql api。我已经浏览了文档,但我仍然不知道如何链接过滤器,特别是检查authorization
在请求头中。
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
with .and(warp::header::<String>("authorization")
,然后它拒绝所有不包含的请求authorization
在标题中。
我怎样才能使
如果请求标头有authorization
在标题中,然后返回Context
与适当的user_id
如果没有,则返回Context
with user_id: 0
?
我找到了solution https://github.com/seanmonstar/warp/issues/177#issuecomment-469497434在 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(),
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)