revoke-auth 0.5.0

High-performance microservices infrastructure framework built with pure Rust
Documentation
use crate::{claims::JwtClaims, jwks::JwksStore};
use anyhow::{Result, anyhow};
use jsonwebtoken::{Validation, decode, decode_header};

pub async fn validate_token<T: JwtClaims>(
    token: &str,
    jwks: &JwksStore,
    expected_issuer: &str,
    expected_audience: Option<&str>,
) -> Result<T> {
    let header = decode_header(token)?;
    let kid = header.kid.ok_or_else(|| anyhow!("Missing kid"))?;
    let key = jwks
        .get_key(&kid)
        .await
        .ok_or_else(|| anyhow!("Key not found"))?;

    let mut validation = Validation::new(header.alg);
    validation.set_issuer(&[expected_issuer]);
    if let Some(aud) = expected_audience {
        validation.set_audience(&[aud]);
    }

    let token_data = decode::<T>(token, &key, &validation)?;
    Ok(token_data.claims)
}