How to check the authorization header using Warp?
Asked Answered
E

1

9

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()

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.

How can I make

  1. if request header has a authorization in header, then return Context with the proper user_id

  2. if not, return Context with user_id: 0?

Epistemic answered 4/3, 2019 at 17:23 Comment(0)
E
11

I've found the solution in github issues of Warp.

here is a small snippet.

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(),
);
Epistemic answered 5/3, 2019 at 2:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.