Files
compliance-scanner-agent/compliance-dashboard/src/infrastructure/auth_middleware.rs
Sharang Parnerkar b8b0f13d8d
Some checks failed
CI / Format (push) Failing after 2s
CI / Clippy (push) Successful in 2m54s
CI / Security Audit (push) Has been skipped
CI / Tests (push) Has been skipped
CI / Clippy (pull_request) Successful in 3m4s
CI / Security Audit (pull_request) Has been skipped
CI / Tests (pull_request) Has been skipped
CI / Format (pull_request) Failing after 2s
Make Keycloak authentication optional for local development
When KEYCLOAK_URL is not set, the dashboard runs without auth,
treating all users as authenticated "Local User". Auth middleware
and check-auth endpoint gracefully skip when Keycloak is unconfigured.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:32:29 +01:00

46 lines
1.2 KiB
Rust

use axum::{
extract::Request,
middleware::Next,
response::{IntoResponse, Response},
Extension,
};
use reqwest::StatusCode;
use tower_sessions::Session;
use super::auth::LOGGED_IN_USER_SESS_KEY;
use super::server_state::ServerState;
use super::user_state::UserStateInner;
const PUBLIC_API_ENDPOINTS: &[&str] = &["/api/check-auth"];
/// Axum middleware that enforces authentication on `/api/` server
/// function endpoints. Skips auth entirely when Keycloak is not configured.
pub async fn require_auth(
Extension(state): Extension<ServerState>,
session: Session,
request: Request,
next: Next,
) -> Response {
// Skip auth when Keycloak is not configured
if state.keycloak.is_none() {
return next.run(request).await;
}
let path = request.uri().path();
if path.starts_with("/api/") && !PUBLIC_API_ENDPOINTS.contains(&path) {
let is_authed = session
.get::<UserStateInner>(LOGGED_IN_USER_SESS_KEY)
.await
.ok()
.flatten()
.is_some();
if !is_authed {
return (StatusCode::UNAUTHORIZED, "Authentication required").into_response();
}
}
next.run(request).await
}