jwt_verify/integration/
axum.rs

1#[cfg(feature = "axum-integration")]
2pub mod axum_integration {
3    use axum::http::HeaderMap;
4    use axum::response::{IntoResponse, Response};
5    use axum::http::StatusCode;
6
7    use crate::common::error::{JwtError, PublicJwtError};
8    use crate::integration::Headers;
9
10    /// Implementation of Headers for Axum's HeaderMap
11    impl Headers for HeaderMap {
12        fn get(&self, name: &str) -> Option<&str> {
13            self.get(name).and_then(|v| v.to_str().ok())
14        }
15    }
16
17    /// Extension trait to convert JwtError to Axum HTTP responses
18    pub trait JwtErrorResponse {
19        /// Convert the error to an HTTP response with appropriate status code
20        fn into_response(self) -> Response;
21    }
22
23    impl JwtErrorResponse for JwtError {
24        fn into_response(self) -> Response {
25            // Convert to public error first to sanitize sensitive information
26            let public_error: PublicJwtError = self.into();
27            public_error.into_response()
28        }
29    }
30
31    impl IntoResponse for PublicJwtError {
32        fn into_response(self) -> Response {
33            // All public errors map to UNAUTHORIZED status code
34            let status_code = StatusCode::UNAUTHORIZED;
35            
36            // Create a JSON response with the error message
37            let body = serde_json::json!({
38                "error": self.to_string(),
39                "status": "error",
40                "code": status_code.as_u16()
41            });
42            
43            // Return the status code and JSON body
44            (status_code, axum::Json(body)).into_response()
45        }
46    }
47}