refactor: middlewares folder
CI / Rust CI (push) Successful in 1m37s
Publish & Deploy / Build and Push to Registry (push) Successful in 24s
Publish & Deploy / Deploy via SSH (push) Successful in 17s

This commit is contained in:
2026-04-11 20:35:36 +02:00
parent e1f46c07b4
commit f4da65dbc2
8 changed files with 7 additions and 3 deletions
+59
View File
@@ -0,0 +1,59 @@
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::env;
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Claims {
pub sub: String,
pub preferred_username: Option<String>,
pub exp: usize,
pub iss: String,
pub aud: Option<String>,
pub realm_access: Option<RealmAccess>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RealmAccess {
pub roles: Vec<String>,
}
static ISSUER: Lazy<String> = Lazy::new(|| env::var("ISSUER").expect("ISSUER not set"));
pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
// 1. Decode header
let header = decode_header(token).map_err(|_| "Invalid header")?;
let kid = header.kid.ok_or("Missing kid")?;
// 2. Find matching key
let keys = jwks["keys"].as_array().ok_or("Invalid JWKS")?;
let key = keys
.iter()
.find(|k| k["kid"] == kid)
.ok_or("Matching key not found")?;
// 3. Extract RSA components
let n = key["n"].as_str().ok_or("Missing n")?;
let e = key["e"].as_str().ok_or("Missing e")?;
let decoding_key =
DecodingKey::from_rsa_components(n, e).map_err(|_| "Invalid decoding key")?;
// 4. Setup validation rules
let mut validation = Validation::new(Algorithm::RS256);
validation.set_issuer(&[ISSUER.as_str()]);
// Optional but recommended:
validation.validate_exp = true;
validation.validate_aud = false; // depends on your Keycloak config
// 5. Decode & verify
let token_data = decode::<Claims>(token, &decoding_key, &validation)
.map_err(|_| "Token validation failed")?;
Ok(token_data.claims)
}
+57
View File
@@ -0,0 +1,57 @@
use once_cell::sync::Lazy;
use serde_json::Value;
use std::env;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
#[derive(Clone)]
struct JwksCache {
jwks: Value,
last_fetched: Instant,
}
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> = Lazy::new(|| Arc::new(RwLock::new(None)));
static JWKS_URL: Lazy<String> = Lazy::new(|| env::var("JWKS_URL").expect("JWKS_URL not set"));
async fn fetch_jwks() -> Result<Value, reqwest::Error> {
let jwks = reqwest::get(JWKS_URL.as_str())
.await?
.json::<Value>()
.await?;
Ok(jwks)
}
pub async fn refresh_jwks() -> Result<Value, reqwest::Error> {
let jwks = fetch_jwks().await?;
let mut write = JWK_CACHE.write().await;
*write = Some(JwksCache {
jwks: jwks.clone(),
last_fetched: Instant::now(),
});
Ok(jwks)
}
pub async fn get_jwks() -> Result<Value, reqwest::Error> {
let ttl = Duration::from_secs(3600); // 1 hour
{
// Read lock first (fast path)
let read = JWK_CACHE.read().await;
if let Some(cache) = read
.as_ref()
.filter(|cache| cache.last_fetched.elapsed() < ttl)
{
return Ok(cache.jwks.clone());
}
}
// Expired or empty → refresh
refresh_jwks().await
}
+51
View File
@@ -0,0 +1,51 @@
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
use crate::middlewares::auth::{
jwt::validate_token,
keycloak::{get_jwks, refresh_jwks},
};
pub async fn auth_middleware(mut request: Request, next: Next) -> Result<Response, StatusCode> {
#[cfg(debug_assertions)]
println!("Middleware hit");
let headers = request.headers();
#[cfg(debug_assertions)]
println!("Headers extracted");
let auth_header = headers.get("authorization").and_then(|v| v.to_str().ok());
#[cfg(debug_assertions)]
println!("Auth header: {:?}", auth_header);
let auth_header = auth_header.ok_or(StatusCode::UNAUTHORIZED)?;
let token = auth_header
.strip_prefix("Bearer ")
.ok_or(StatusCode::UNAUTHORIZED)?;
let jwks = get_jwks().await.map_err(|_| StatusCode::UNAUTHORIZED)?;
match validate_token(token, &jwks) {
Ok(claims) => {
#[cfg(debug_assertions)]
println!("Token valid");
request.extensions_mut().insert(claims);
Ok(next.run(request).await)
}
Err(_) => {
let jwks = refresh_jwks().await.map_err(|_| StatusCode::UNAUTHORIZED)?;
match validate_token(token, &jwks) {
Ok(claims) => {
request.extensions_mut().insert(claims);
Ok(next.run(request).await)
}
Err(_) => Err(StatusCode::UNAUTHORIZED),
}
}
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod jwt;
pub mod keycloak;
pub mod middleware;
pub use middleware::auth_middleware;
+1
View File
@@ -0,0 +1 @@
pub mod auth;