feat: add auth middleware

This commit is contained in:
2026-04-09 15:31:55 +02:00
parent 5eb8da88f8
commit 05bc471d01
11 changed files with 176 additions and 46 deletions
+33 -14
View File
@@ -1,9 +1,10 @@
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::env;
use once_cell::sync::Lazy;
static ISSUER: &str = "https://auth.iceberg.black/realms/iceberg";
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Claims {
pub sub: String,
pub preferred_username: Option<String>,
@@ -13,34 +14,52 @@ pub struct Claims {
pub realm_access: Option<RealmAccess>,
}
#[derive(Debug, Deserialize, Serialize)]
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct RealmAccess {
pub roles: Vec<String>,
}
pub fn validate_token(token: &str, jwks: &serde_json::Value) -> Result<Claims, ()> {
let header = decode_header(token).map_err(|_| ())?;
static ISSUER: Lazy<String> = Lazy::new(|| {
env::var("ISSUER").expect("ISSUER not set")
});
let kid = header.kid.ok_or(())?;
pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
// 1. Decode header
let header = decode_header(token).map_err(|_| "Invalid header")?;
let keys = jwks["keys"].as_array().ok_or(())?;
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(())?;
.ok_or("Matching key not found")?;
let n = key["n"].as_str().ok_or(())?;
let e = key["e"].as_str().ok_or(())?;
// 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(|_| ())?;
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]);
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(|_| ())?;
decode::<Claims>(token, &decoding_key, &validation)
.map_err(|_| "Token validation failed")?;
Ok(token_data.claims)
}