mas_oidc_client/requests/
token.rs1use chrono::{DateTime, Utc};
10use http::header::ACCEPT;
11use mas_http::RequestBuilderExt;
12use mime::APPLICATION_JSON;
13use oauth2_types::requests::{AccessTokenRequest, AccessTokenResponse};
14use rand::Rng;
15use url::Url;
16
17use crate::{
18    error::{ResponseExt, TokenRequestError},
19    types::client_credentials::ClientCredentials,
20};
21
22#[tracing::instrument(skip_all, fields(token_endpoint, request))]
43pub async fn request_access_token(
44    http_client: &reqwest::Client,
45    client_credentials: ClientCredentials,
46    token_endpoint: &Url,
47    request: AccessTokenRequest,
48    now: DateTime<Utc>,
49    rng: &mut impl Rng,
50) -> Result<AccessTokenResponse, TokenRequestError> {
51    tracing::debug!(?request, "Requesting access token...");
52
53    let token_request = http_client
54        .post(token_endpoint.as_str())
55        .header(ACCEPT, APPLICATION_JSON.as_ref());
56
57    let token_response = client_credentials
58        .authenticated_form(token_request, &request, now, rng)?
59        .send_traced()
60        .await?
61        .error_from_oauth2_error_response()
62        .await?
63        .json()
64        .await?;
65
66    Ok(token_response)
67}