auth0-integration 0.6.1

Auth0 client library for M2M token retrieval and JWT validation (RS256)
Documentation
use serde::Serialize;

use crate::{config::Auth0Config, error::AppError, models::AccessTokenResponse, services::HttpClient};

#[derive(Debug, Serialize)]
struct ClientCredentialsRequest<'a> {
    grant_type: &'a str,
    client_id: &'a str,
    client_secret: &'a str,
    audience: &'a str,
}

pub struct Auth0ClientToken {
    http: HttpClient,
    config: Auth0Config,
}

impl Auth0ClientToken {
    pub fn new(config: &Auth0Config) -> Self {
        let http = HttpClient::new(config);
        Self { http, config: config.clone() }
    }

    /// Obtain a machine-to-machine access token via client credentials flow.
    pub async fn get_access_token(&self) -> Result<AccessTokenResponse, AppError> {
        let body = ClientCredentialsRequest {
            grant_type: "client_credentials",
            client_id: &self.config.auth0_client_id,
            client_secret: &self.config.auth0_client_secret,
            audience: &self.config.auth0_audience,
        };

        let res = self.http.post("/oauth/token", &body).await?;

        if !res.status().is_success() {
            let text = res.text().await.unwrap_or_default();
            return Err(AppError::Auth0(text));
        }

        Ok(res.json::<AccessTokenResponse>().await?)
    }
}