|
| 1 | +use std::sync::Arc; |
| 2 | +use axum::extract::State; |
| 3 | +use axum::http::{header, HeaderMap, HeaderValue, Response, StatusCode}; |
| 4 | +use axum::response::IntoResponse; |
| 5 | +use crate::gateway::{ApiGatewayState, GatewayAuthContextRef, GatewayAuthService, GatewayCheckAuthRequest}; |
| 6 | +use crate::gateway::http_error::HttpError; |
| 7 | + |
| 8 | +#[derive(Debug, Clone)] |
| 9 | +pub struct AuthExtension { |
| 10 | + auth_context: GatewayAuthContextRef, |
| 11 | +} |
| 12 | + |
| 13 | +pub async fn gateway_auth_middleware( |
| 14 | + State(state): State<ApiGatewayState>, |
| 15 | + mut req: axum::extract::Request, |
| 16 | + next: axum::middleware::Next, |
| 17 | +) -> Result<impl IntoResponse, HttpError> { |
| 18 | + let Some(token_header_value) = req.headers().get("authorization") else { |
| 19 | + return Err(HttpError::unauthorized("No authorization header".to_string())); |
| 20 | + }; |
| 21 | + |
| 22 | + let auth = state |
| 23 | + .injector_ref() |
| 24 | + .get_service_typed::<dyn GatewayAuthService>() |
| 25 | + .await; |
| 26 | + |
| 27 | + let auth_fut = auth.authenticate( |
| 28 | + GatewayCheckAuthRequest { |
| 29 | + protocol: "http".to_string(), |
| 30 | + }, |
| 31 | + token_header_value.to_str()?.to_string() |
| 32 | + ); |
| 33 | + |
| 34 | + let auth_response = auth_fut.await.map_err(|err| {; |
| 35 | + HttpError::unauthorized("Authentication error".to_string()) |
| 36 | + })?; |
| 37 | + |
| 38 | + req.extensions_mut().insert(AuthExtension { auth_context: auth_response.context }); |
| 39 | + |
| 40 | + let response = next.run(req).await; |
| 41 | + Ok(response) |
| 42 | +} |
0 commit comments