Possible to pass extension/args to basic middleware functions? #1829
-
use axum::{
Router,
http::{Request, StatusCode},
routing::get,
response::{IntoResponse, Response},
middleware::{self, Next},
extract::Extension,
};
#[derive(Clone)]
struct CurrentUser { /* ... */ }
async fn auth<B>(mut req: Request<B>, next: Next<B>, config: Config) -> Result<Response, StatusCode> {
let auth_header = req.headers()
.get(http::header::AUTHORIZATION)
.and_then(|header| header.to_str().ok());
let auth_header = if let Some(auth_header) = auth_header {
auth_header
} else {
return Err(StatusCode::UNAUTHORIZED);
};
if let Some(current_user) = authorize_current_user(auth_header, config).await {
// insert the current user into a request extension so the handler can
// extract it
req.extensions_mut().insert(current_user);
Ok(next.run(req).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn authorize_current_user(auth_token: &str, config: Config) -> Option<CurrentUser> {
// authorize the user using `auth_token`, but based on some value in `Config`
}
async fn handler(
// extract the current user, set by the middleware
Extension(current_user): Extension<CurrentUser>,
) {
// ...
}
let app = Router::new()
.route("/", get(handler))
.route_layer(middleware::from_fn(auth)); |
Beta Was this translation helpful? Give feedback.
Answered by
davidpdrsn
Mar 8, 2023
Replies: 1 comment 3 replies
-
Yes. See https://docs.rs/axum/latest/axum/middleware/index.html#accessing-state-in-axummiddlewarefrom_fn |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
ra0x3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes. See https://docs.rs/axum/latest/axum/middleware/index.html#accessing-state-in-axummiddlewarefrom_fn