+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)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user