-
Bug ReportVersionaxum = { 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 (*) PlatformLinux 4eb828285a59 5.15.49-linuxkit #1 SMP Tue Sep 13 07:51:46 UTC 2022 x86_64 GNU/Linux DescriptionI'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(¤t_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))
} |
Beta Was this translation helpful? Give feedback.
Answered by
jifalops
Jul 2, 2023
Replies: 1 comment 2 replies
-
Setting request extensions in middleware does work. So for some reason that line doesn't run in your middleware. Have you checked if any of the early returns are hit? Otherwise please reduce it to a minimal example that we can run. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The line does print:
debug!("middleware: adding user to request extensions");
On mobile now, will add runnable example later.
Edit: It must be in CurrentUser::new(), which takes a json Value and does some parsing.