如何使用Warp检查授权标头?

问题描述 投票:1回答:1

我正在用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建立了一条路线.and(warp::header::<String>("authorization"),然后它拒绝了所有在标题中不包含authorization的请求。

我该怎么做

  1. 如果请求标头在标头中有authorization,则返回Context并使用正确的user_id
  2. 如果没有,请与Context一起返回user_id: 0
rust
1个回答
1
投票

我在Warp的github问题中找到了solution

这是一个小片段。

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(),
);
© www.soinside.com 2019 - 2024. All rights reserved.