How to add arguments to reqwest_middleware per request?

I'm building an API service using Axum, and my service communicate with other third party services (using reqwest) on behalf of the user. Right now, I'm trying to implement a middleware that would handle refreshing user's expired access_token. The problem is that for each request, my middleware needs to know the user's id so it can fetch that user's refresh token from redis. I could add a user_id field to the RefreshTokenMiddleware struct and create a new client for every request with the user's id, but I really don't want to do that.. so I wonder if there's a way I can add an argument to the existing client? Below is a simplified version of my code. Any help/suggestions would be greatly appreciated!

struct RefreshTokenMiddleware;
impl Middleware for RefreshTokenMiddleware {
    async fn handle(
        req: Request,
        extensions: &mut Extensions,
        next: Next<'_>,
    ) -> reqwest_middleware::Result<Response> {
       // Need to access user_id in here to fetch refresh_token....

// In Third Party Service
async fn get_data(client: ClientWithMiddleware, user_id: String) {
     // Is it possible to pass user_id into the client middleware from here?
        .header(AUTHORIZATION, "Bearer expired-token")

async fn main() {
    let client = ClientBuilder::new(reqwest::Client::new())
       let app_state = AppState { db: db_pool, reqwest_client: client };

You could give try solving your use case through middleware extensions. I quickly check the documentation, and it seems that it's possible to pass data to the middleware from the request handler with it.

Don't you have to pass user_id as part of the request anyway? I.e. as a header or cookie or in the query parameters or something? Or where is it coming from?

No because the user_id belongs to my system and I'm sending a request to a third party api. However, this problem is solved by using RequestBuilder::with_extensions(). I just need to get better at reading the docs.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.