jwt-verify 0.1.0

JWT verification library for AWS Cognito tokens and any OIDC-compatible IDP
Documentation
//! Integration with web frameworks
//!
//! This module provides utilities for integrating the JWT verification library
//! with various web frameworks. It includes framework-agnostic token extraction
//! utilities that can be used with any web framework.

pub mod extractor;

// Re-export commonly used types
pub use extractor::{
    ChainedTokenExtractor, DebugTokenExtractor, HeaderTokenExtractor, Headers, TokenExtractor, TokenExtractorConfig,
};

/// Core token extraction and verification functions
pub mod core {
    use crate::claims::{CognitoAccessTokenClaims, CognitoIdTokenClaims};
    use crate::common::error::JwtError;
    use crate::integration::Headers;
    use crate::verifier::CognitoJwtVerifier;
    use crate::JwtVerifier;

    /// Extract a token from headers with an optional prefix
    ///
    /// # Parameters
    ///
    /// * `headers` - The headers to extract the token from
    /// * `header_name` - The name of the header to extract the token from
    /// * `token_prefix` - Optional prefix to remove from the token (e.g., "Bearer ")
    ///
    /// # Returns
    ///
    /// Returns an `Option<String>` with the token if found, or `None` if not found.
    pub fn extract_token<H: Headers>(
        headers: &H,
        header_name: &str,
        token_prefix: Option<&str>,
    ) -> Result<Option<String>, JwtError> {
        // Check if the header exists
        let header_str = match headers.get(header_name) {
            Some(value) => value,
            None => return Ok(None), // Header not found
        };

        // If a token prefix is specified, check if the header value starts with it
        if let Some(prefix) = token_prefix {
            if !header_str.starts_with(prefix) {
                return Err(JwtError::InvalidToken(format!(
                    "{} header must start with '{}'",
                    header_name, prefix
                )));
            }

            // Remove the prefix and return the token
            Ok(Some(header_str[prefix.len()..].to_string()))
        } else {
            // No prefix, return the entire header value
            Ok(Some(header_str.to_string()))
        }
    }

    /// Extract a Bearer token from headers
    ///
    /// # Parameters
    ///
    /// * `headers` - The headers to extract the token from
    /// * `header_name` - The name of the header to extract the token from
    ///
    /// # Returns
    ///
    /// Returns an `Option<String>` with the token if found, or `None` if not found.
    pub fn extract_bearer_token<H: Headers>(
        headers: &H,
        header_name: &str,
    ) -> Result<Option<String>, JwtError> {
        extract_token(headers, header_name, Some("Bearer "))
    }

    /// Verify an ID token
    ///
    /// # Parameters
    ///
    /// * `verifier` - The JWT verifier to use
    /// * `token` - The token to verify
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the verified claims if successful, or a `JwtError` if verification fails.
    pub async fn verify_id_token(
        verifier: &CognitoJwtVerifier,
        token: &str,
    ) -> Result<CognitoIdTokenClaims, JwtError> {
        // Use the generic verify method directly to get the concrete type
        verifier.verify::<CognitoIdTokenClaims>(token).await
    }

    /// Verify an access token
    ///
    /// # Parameters
    ///
    /// * `verifier` - The JWT verifier to use
    /// * `token` - The token to verify
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the verified claims if successful, or a `JwtError` if verification fails.
    pub async fn verify_access_token(
        verifier: &CognitoJwtVerifier,
        token: &str,
    ) -> Result<CognitoAccessTokenClaims, JwtError> {
        // Use the generic verify method directly to get the concrete type
        verifier.verify::<CognitoAccessTokenClaims>(token).await
    }
}

// Conditionally include framework-specific integrations
#[cfg(feature = "axum-integration")]
pub mod axum;