Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the authorization header using Warp?

Tags:

rust

rust-warp

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?

like image 689
moondaddi Avatar asked Mar 04 '19 17:03

moondaddi


1 Answers

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(),
);
like image 61
moondaddi Avatar answered Oct 29 '22 21:10

moondaddi