feat: fetch keycloak jwks + cache
This commit is contained in:
@@ -0,0 +1 @@
|
||||
JWKS_URL=https://auth.iceberg.black/realms/iceberg/protocol/openid-connect/certs
|
||||
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+2144
File diff suppressed because it is too large
Load Diff
+14
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "chat"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
axum = "0.8.8"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
jsonwebtoken = "10.3.0"
|
||||
reqwest = { version = "0.13.2", features = ["json"] }
|
||||
once_cell = "1"
|
||||
dotenvy = "0.15"
|
||||
@@ -0,0 +1,46 @@
|
||||
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
static ISSUER: &str = "https://auth.iceberg.black/realms/iceberg";
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
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)]
|
||||
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(|_| ())?;
|
||||
|
||||
let kid = header.kid.ok_or(())?;
|
||||
|
||||
let keys = jwks["keys"].as_array().ok_or(())?;
|
||||
|
||||
let key = keys
|
||||
.iter()
|
||||
.find(|k| k["kid"] == kid)
|
||||
.ok_or(())?;
|
||||
|
||||
let n = key["n"].as_str().ok_or(())?;
|
||||
let e = key["e"].as_str().ok_or(())?;
|
||||
|
||||
let decoding_key =
|
||||
DecodingKey::from_rsa_components(n, e).map_err(|_| ())?;
|
||||
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
validation.set_issuer(&[ISSUER]);
|
||||
|
||||
let token_data =
|
||||
decode::<Claims>(token, &decoding_key, &validation).map_err(|_| ())?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use serde_json::Value;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::env;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct JwksCache {
|
||||
jwks: Value,
|
||||
last_fetched: Instant,
|
||||
}
|
||||
|
||||
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> =
|
||||
Lazy::new(|| Arc::new(RwLock::new(None)));
|
||||
|
||||
async fn fetch_jwks() -> Result<Value, reqwest::Error> {
|
||||
let url = env::var("JWKS_URL").expect("JWKS_URL not set");
|
||||
|
||||
let jwks = reqwest::get(url)
|
||||
.await?
|
||||
.json::<Value>()
|
||||
.await?;
|
||||
|
||||
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 {
|
||||
if cache.last_fetched.elapsed() < ttl {
|
||||
return Ok(cache.jwks.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Expired or empty → refresh
|
||||
let jwks = fetch_jwks().await?;
|
||||
|
||||
let mut write = JWK_CACHE.write().await;
|
||||
|
||||
*write = Some(JwksCache {
|
||||
jwks: jwks.clone(),
|
||||
last_fetched: Instant::now(),
|
||||
});
|
||||
|
||||
Ok(jwks)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod jwt;
|
||||
pub mod keycloak;
|
||||
// pub mod middleware;
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
mod auth;
|
||||
|
||||
use crate::auth::{keycloak, jwt};
|
||||
|
||||
use axum::{
|
||||
extract::Request,
|
||||
http::{HeaderMap, StatusCode},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use dotenvy::dotenv;
|
||||
use std::env;
|
||||
|
||||
|
||||
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
dotenv().ok();
|
||||
|
||||
let jwks = keycloak::get_jwks().await;
|
||||
|
||||
println!("{:?}", jwks);
|
||||
|
||||
// let app = Router::new().route("/protected", get(protected_route))
|
||||
// .route("/", get(dumb));
|
||||
|
||||
// let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
||||
// println!("Server running on {}", addr);
|
||||
|
||||
// axum::serve(tokio::net::TcpListener::bind(addr).await.unwrap(), app)
|
||||
// .await
|
||||
// .unwrap();
|
||||
}
|
||||
Reference in New Issue
Block a user