+8
-14
@@ -1,8 +1,8 @@
|
||||
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
|
||||
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode, decode_header};
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::env;
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct Claims {
|
||||
@@ -19,9 +19,7 @@ pub struct RealmAccess {
|
||||
pub roles: Vec<String>,
|
||||
}
|
||||
|
||||
static ISSUER: Lazy<String> = Lazy::new(|| {
|
||||
env::var("ISSUER").expect("ISSUER not set")
|
||||
});
|
||||
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
|
||||
@@ -30,9 +28,7 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
|
||||
let kid = header.kid.ok_or("Missing kid")?;
|
||||
|
||||
// 2. Find matching key
|
||||
let keys = jwks["keys"]
|
||||
.as_array()
|
||||
.ok_or("Invalid JWKS")?;
|
||||
let keys = jwks["keys"].as_array().ok_or("Invalid JWKS")?;
|
||||
|
||||
let key = keys
|
||||
.iter()
|
||||
@@ -44,8 +40,7 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
|
||||
let e = key["e"].as_str().ok_or("Missing e")?;
|
||||
|
||||
let decoding_key =
|
||||
DecodingKey::from_rsa_components(n, e)
|
||||
.map_err(|_| "Invalid decoding key")?;
|
||||
DecodingKey::from_rsa_components(n, e).map_err(|_| "Invalid decoding key")?;
|
||||
|
||||
// 4. Setup validation rules
|
||||
let mut validation = Validation::new(Algorithm::RS256);
|
||||
@@ -57,9 +52,8 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
|
||||
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")?;
|
||||
let token_data = decode::<Claims>(token, &decoding_key, &validation)
|
||||
.map_err(|_| "Token validation failed")?;
|
||||
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-15
@@ -1,9 +1,9 @@
|
||||
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;
|
||||
use serde_json::Value;
|
||||
use std::env;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct JwksCache {
|
||||
@@ -11,12 +11,9 @@ struct JwksCache {
|
||||
last_fetched: Instant,
|
||||
}
|
||||
|
||||
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> =
|
||||
Lazy::new(|| Arc::new(RwLock::new(None)));
|
||||
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")
|
||||
});
|
||||
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())
|
||||
@@ -47,13 +44,14 @@ pub async fn get_jwks() -> Result<Value, reqwest::Error> {
|
||||
// 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());
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
+8
-15
@@ -1,25 +1,18 @@
|
||||
use axum::{
|
||||
extract::Request,
|
||||
http::{StatusCode},
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
|
||||
|
||||
use crate::auth::{
|
||||
jwt::validate_token,
|
||||
keycloak::{get_jwks, refresh_jwks},
|
||||
};
|
||||
|
||||
use crate::auth::{jwt::validate_token, keycloak::{get_jwks, refresh_jwks}};
|
||||
|
||||
pub async fn auth_middleware(
|
||||
mut request: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
pub async fn auth_middleware(mut request: Request, next: Next) -> Result<Response, StatusCode> {
|
||||
dbg!("Middleware hit");
|
||||
|
||||
let headers = request.headers();
|
||||
|
||||
dbg!("Headers extracted");
|
||||
|
||||
let auth_header = headers
|
||||
.get("authorization")
|
||||
.and_then(|v| v.to_str().ok());
|
||||
let auth_header = headers.get("authorization").and_then(|v| v.to_str().ok());
|
||||
|
||||
dbg!("Auth header: {:?}", auth_header);
|
||||
|
||||
@@ -51,4 +44,4 @@ pub async fn auth_middleware(
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
pub mod jwt;
|
||||
pub mod keycloak;
|
||||
pub mod middleware;
|
||||
pub mod middleware;
|
||||
|
||||
Reference in New Issue
Block a user