rust - 如何使用 Warp 检查授权 header ?

标签 rust rust-warp

我正在使用 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 的请求在标题中。

我该怎么做

  1. 如果请求头有 authorization在标题中,然后返回 Context使用适当的 user_id

  2. 如果不是,返回Contextuser_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/

相关文章:

rust - 无法为我自己的类型实现任意快速检查 - "source trait is private"

rust - 在泛型类型声明中使用一组空括号意味着什么?

rust - 性状std::convert::From <String>不适用于hyper::body::Body

websocket - 为变形过滤器重用已移动的变量

rust - 是否有更简单的方法来创建自定义 Filter 方法来调用 Warp 处理程序?

rust - 重命名匹配中的枚举字段 (rust)

csv - serde 缺少字段无法设置为默认值

methods - 翘曲的根路径示例?

rust - 令人困惑的借用检查器消息 : "lifetime mismatch"