Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missing request extension (500) when passing state from middleware fn to handler, similar to example. #2070

Closed
1 task done
jifalops opened this issue Jul 2, 2023 · 0 comments

Comments

@jifalops
Copy link

jifalops commented Jul 2, 2023

  • I have looked for existing issues (including closed) about this

Bug Report

Version

axum = { version = "0.6.18", features=["macros"] }
├── axum v0.6.18
│   ├── axum-core v0.3.4
│   ├── axum-macros v0.3.7 (proc-macro)
├── axum-aws-lambda v0.5.0
│   ├── axum v0.6.18 (*)
│   ├── axum v0.6.18 (*)

Platform

Linux 4eb828285a59 5.15.49-linuxkit #1 SMP Tue Sep 13 07:51:46 UTC 2022 x86_64 GNU/Linux

Description

I'm getting a 500 error for middleware that is very similar to the example.

I thought this had worked before but now I have a pretty simple test that I can't get to pass.

cargo test middleware_runs
Body: Missing request extension: Extension of type `fs::user::CurrentUser` was not found. Perhaps you forgot to add it? See `axum::Extension`.
pub async fn current_user_middleware<B>(
    mut req: Request<B>,
    next: Next<B>,
) -> Result<Response, StatusCode> {
    let token = match Token::from_request(&req) {
        Some(t) => t,
        None => return Err(StatusCode::UNAUTHORIZED),
    };
    let claims = match token.into_claims() {
        Ok(d) => d,
        Err(_e) => return Err(StatusCode::UNAUTHORIZED),
    };
    debug!("middleware: adding user to request extensions");
    req.extensions_mut().insert(CurrentUser::new(claims));
    Ok(next.run(req).await)
}

...

#[tokio::test]
async fn middleware_runs() {
    async fn handler(Extension(current_user): Extension<CurrentUser>) {
        serde_json::to_string(&current_user).unwrap();
    }
    let router = Router::new()
        .route("/", get(handler))
        .route_layer(middleware::from_fn(current_user_middleware));

    let req = Request::builder()
        .uri("/")
        .header("Authorization", DEV_TOKEN)
        .body(Body::empty())
        .unwrap();
    let res = router.oneshot(req).await.unwrap();
    let body = res.into_body_string().await.unwrap();
    println!("Body: {}", body); // Body: Missing request extension: Extension of type `fs::user::CurrentUser` was not found. Perhaps you forgot to add it? See `axum::Extension`.
    // Fails with 500 error.
    // assert_eq!(res.status(), StatusCode::OK);
    assert!(body.contains(DEV_TOKEN_UID))
}

// Response extensions used above.
async fn into_body_string(self) -> Result<String> {
    let bytes = self.into_body_bytes().await?;
    String::from_utf8(bytes.to_vec()).map_err(|e| anyhow!(e))
}
async fn into_body_bytes(self) -> Result<Bytes> {
    hyper::body::to_bytes(self.into_body())
        .await
        .map_err(|e| anyhow!(e))
}
@tokio-rs tokio-rs locked and limited conversation to collaborators Jul 2, 2023
@davidpdrsn davidpdrsn converted this issue into discussion #2071 Jul 2, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant