I know this looks like a very basic and silly question. But I have been unabele to solve this.
In my rust application, I am using a middleware to create validate JWT and then passing on to next handler like below.
pub async fn jwt_validator(mut req: Request, next: Next) -> Result<Response, StatusCode> {
// exclude some non protected endpoints
let exclusion_list = vec!["/login", "/signup", "/welcome"];
let path = req.uri().path();
trace!("Checking exclusion list for path: {}...", path);
// Check if the path contains or ends with any of the exclusion list items
if exclusion_list
.iter()
.any(|item| path.contains(item) || path.ends_with(item))
{
trace!("Skipping jwt validation for path: {}", path);
return Ok(next.run(req).await);
}
let auth_header = req.headers().get("Authorization");
if let Some(auth_header) = auth_header {
if let Ok(auth_str) = auth_header.to_str() {
if auth_str.starts_with("Bearer ") {
let token = &auth_str[7..];
// If validation successful, add the claims to the request extensions
if let Ok(claims) = validate_jwt(token) {
trace!("Token validated successfully: {:?}", claims);
req.extensions_mut().insert(Arc::new(claims));
return Ok(next.run(req).await);
}
}
}
}
Err(StatusCode::UNAUTHORIZED)
}
And the handler fn that executes after the jwt validator.
pub async fn create_workflow(
Extension(conn): Extension<DatabaseConnection>,
Extension(payload): Extension<Value>,
Extension(claims): Extension<Arc<Claims>>,
) -> impl IntoResponse {
trace!("Executing create_workflow handler..");
// print the claims
trace!("Claims: {:?}", claims);
// Create a new uuid for workflow item.
let workflow_id = uuid::Uuid::new_v4();
// Extract customer id from token
let cust_id = uuid::Uuid::parse_str(&claims.sub).unwrap();
...
The middleware jwt validator seems to be working correctly, i.e validating the token and inserting the claims into the request for the next handler to consume. Here are the trace logs which confirm that the mw is inserting the claims data into request.
[2024-08-04T13:17:03Z TRACE workflow_cruder::middlewares::jwt_validator] Checking exclusion list for path: /api/v1/workflows...
[2024-08-04T13:17:03Z TRACE workflow_cruder::middlewares::jwt_validator] Token validated successfully: Claims { sub: "accedbaa-2c19-41bd-a7ef-f2257578f337", exp: 1722779401 }
[2024-08-04T13:17:03Z TRACE axum::rejection] rejecting request status=500 body="Missing request extension: Extension of type `serde_json::value::Value` was not found. Perhaps you forgot to add it? See `axum::Extension`." rejection_type="axum::extract::rejection::MissingExtension"
The first two lines in the above log indicate that the mw is doing its job. But the last line is from the handler which says Extension of type serde_json::value::Value
was not found.
I may be doing some very basic mistake here, but unable to find out what is going wrong here. Thanks in advance for help.