+6
-12
@@ -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::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::env;
|
use std::env;
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||||
pub struct Claims {
|
pub struct Claims {
|
||||||
@@ -19,9 +19,7 @@ pub struct RealmAccess {
|
|||||||
pub roles: Vec<String>,
|
pub roles: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
static ISSUER: Lazy<String> = Lazy::new(|| {
|
static ISSUER: Lazy<String> = Lazy::new(|| env::var("ISSUER").expect("ISSUER not set"));
|
||||||
env::var("ISSUER").expect("ISSUER not set")
|
|
||||||
});
|
|
||||||
|
|
||||||
pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
|
pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
|
||||||
// 1. Decode header
|
// 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")?;
|
let kid = header.kid.ok_or("Missing kid")?;
|
||||||
|
|
||||||
// 2. Find matching key
|
// 2. Find matching key
|
||||||
let keys = jwks["keys"]
|
let keys = jwks["keys"].as_array().ok_or("Invalid JWKS")?;
|
||||||
.as_array()
|
|
||||||
.ok_or("Invalid JWKS")?;
|
|
||||||
|
|
||||||
let key = keys
|
let key = keys
|
||||||
.iter()
|
.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 e = key["e"].as_str().ok_or("Missing e")?;
|
||||||
|
|
||||||
let decoding_key =
|
let decoding_key =
|
||||||
DecodingKey::from_rsa_components(n, e)
|
DecodingKey::from_rsa_components(n, e).map_err(|_| "Invalid decoding key")?;
|
||||||
.map_err(|_| "Invalid decoding key")?;
|
|
||||||
|
|
||||||
// 4. Setup validation rules
|
// 4. Setup validation rules
|
||||||
let mut validation = Validation::new(Algorithm::RS256);
|
let mut validation = Validation::new(Algorithm::RS256);
|
||||||
@@ -57,8 +52,7 @@ pub fn validate_token(token: &str, jwks: &Value) -> Result<Claims, String> {
|
|||||||
validation.validate_aud = false; // depends on your Keycloak config
|
validation.validate_aud = false; // depends on your Keycloak config
|
||||||
|
|
||||||
// 5. Decode & verify
|
// 5. Decode & verify
|
||||||
let token_data =
|
let token_data = decode::<Claims>(token, &decoding_key, &validation)
|
||||||
decode::<Claims>(token, &decoding_key, &validation)
|
|
||||||
.map_err(|_| "Token validation failed")?;
|
.map_err(|_| "Token validation failed")?;
|
||||||
|
|
||||||
Ok(token_data.claims)
|
Ok(token_data.claims)
|
||||||
|
|||||||
+11
-13
@@ -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 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)]
|
#[derive(Clone)]
|
||||||
struct JwksCache {
|
struct JwksCache {
|
||||||
@@ -11,12 +11,9 @@ struct JwksCache {
|
|||||||
last_fetched: Instant,
|
last_fetched: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> =
|
static JWK_CACHE: Lazy<Arc<RwLock<Option<JwksCache>>>> = Lazy::new(|| Arc::new(RwLock::new(None)));
|
||||||
Lazy::new(|| Arc::new(RwLock::new(None)));
|
|
||||||
|
|
||||||
static JWKS_URL: Lazy<String> = Lazy::new(|| {
|
static JWKS_URL: Lazy<String> = Lazy::new(|| env::var("JWKS_URL").expect("JWKS_URL not set"));
|
||||||
env::var("JWKS_URL").expect("JWKS_URL not set")
|
|
||||||
});
|
|
||||||
|
|
||||||
async fn fetch_jwks() -> Result<Value, reqwest::Error> {
|
async fn fetch_jwks() -> Result<Value, reqwest::Error> {
|
||||||
let jwks = reqwest::get(JWKS_URL.as_str())
|
let jwks = reqwest::get(JWKS_URL.as_str())
|
||||||
@@ -47,12 +44,13 @@ pub async fn get_jwks() -> Result<Value, reqwest::Error> {
|
|||||||
// Read lock first (fast path)
|
// Read lock first (fast path)
|
||||||
let read = JWK_CACHE.read().await;
|
let read = JWK_CACHE.read().await;
|
||||||
|
|
||||||
if let Some(cache) = &*read {
|
if let Some(cache) = read
|
||||||
if cache.last_fetched.elapsed() < ttl {
|
.as_ref()
|
||||||
|
.filter(|cache| cache.last_fetched.elapsed() < ttl)
|
||||||
|
{
|
||||||
return Ok(cache.jwks.clone());
|
return Ok(cache.jwks.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Expired or empty → refresh
|
// Expired or empty → refresh
|
||||||
refresh_jwks().await
|
refresh_jwks().await
|
||||||
|
|||||||
+7
-14
@@ -1,25 +1,18 @@
|
|||||||
use axum::{
|
use axum::{extract::Request, http::StatusCode, middleware::Next, response::Response};
|
||||||
extract::Request,
|
|
||||||
http::{StatusCode},
|
use crate::auth::{
|
||||||
middleware::Next,
|
jwt::validate_token,
|
||||||
response::Response,
|
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");
|
dbg!("Middleware hit");
|
||||||
|
|
||||||
let headers = request.headers();
|
let headers = request.headers();
|
||||||
|
|
||||||
dbg!("Headers extracted");
|
dbg!("Headers extracted");
|
||||||
|
|
||||||
let auth_header = headers
|
let auth_header = headers.get("authorization").and_then(|v| v.to_str().ok());
|
||||||
.get("authorization")
|
|
||||||
.and_then(|v| v.to_str().ok());
|
|
||||||
|
|
||||||
dbg!("Auth header: {:?}", auth_header);
|
dbg!("Auth header: {:?}", auth_header);
|
||||||
|
|
||||||
|
|||||||
+7
-18
@@ -1,25 +1,17 @@
|
|||||||
mod auth;
|
mod auth;
|
||||||
|
|
||||||
use crate::auth::middleware::auth_middleware;
|
|
||||||
use crate::auth::jwt::Claims;
|
use crate::auth::jwt::Claims;
|
||||||
|
use crate::auth::middleware::auth_middleware;
|
||||||
|
|
||||||
use dotenvy::dotenv;
|
|
||||||
use axum::extract::Extension;
|
use axum::extract::Extension;
|
||||||
use axum::{
|
use axum::{Router, middleware, routing::get};
|
||||||
routing::get,
|
use dotenvy::dotenv;
|
||||||
Router,
|
|
||||||
middleware,
|
|
||||||
};
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
pub async fn protected_route(
|
pub async fn protected_route(Extension(claims): Extension<Claims>) -> String {
|
||||||
Extension(claims): Extension<Claims>,
|
|
||||||
) -> String {
|
|
||||||
format!(
|
format!(
|
||||||
"Hello {}, your user id is {}",
|
"Hello {}, your user id is {}",
|
||||||
claims
|
claims.preferred_username.unwrap_or("unknown".to_string()),
|
||||||
.preferred_username
|
|
||||||
.unwrap_or("unknown".to_string()),
|
|
||||||
claims.sub
|
claims.sub
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -30,16 +22,13 @@ pub async fn public_route() -> &'static str {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn app() -> Router {
|
pub fn app() -> Router {
|
||||||
let public_routes = Router::new()
|
let public_routes = Router::new().route("/", get(public_route));
|
||||||
.route("/", get(public_route));
|
|
||||||
|
|
||||||
let protected_routes = Router::new()
|
let protected_routes = Router::new()
|
||||||
.route("/protected", get(protected_route))
|
.route("/protected", get(protected_route))
|
||||||
.layer(middleware::from_fn(auth_middleware));
|
.layer(middleware::from_fn(auth_middleware));
|
||||||
|
|
||||||
Router::new()
|
Router::new().merge(public_routes).merge(protected_routes)
|
||||||
.merge(public_routes)
|
|
||||||
.merge(protected_routes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
|
|||||||
Reference in New Issue
Block a user