azure_identity/federated_credentials_flow/mod.rs
1//! Authorize using the OAuth 2.0 client credentials flow with federated credentials.
2//!
3//! ```no_run
4//! use azure_core::{authority_hosts::AZURE_PUBLIC_CLOUD, Url};
5//! use azure_identity::{federated_credentials_flow};
6//!
7//! use std::env;
8//! use std::error::Error;
9//!
10//! #[tokio::main]
11//! async fn main() -> Result<(), Box<dyn Error>> {
12//! let client_id =
13//! env::var("CLIENT_ID").expect("Missing CLIENT_ID environment variable.");
14//! let token = env::var("FEDERATED_TOKEN").expect("Missing FEDERATED_TOKEN environment variable.");
15//! let tenant_id = env::var("TENANT_ID").expect("Missing TENANT_ID environment variable.");
16//! let subscription_id =
17//! env::var("SUBSCRIPTION_ID").expect("Missing SUBSCRIPTION_ID environment variable.");
18//!
19//! let http_client = azure_core::new_http_client();
20//! // This will give you the final token to use in authorization.
21//! let token = federated_credentials_flow::perform(
22//! http_client.clone(),
23//! &client_id,
24//! &token,
25//! &["https://management.azure.com/"],
26//! &tenant_id,
27//! &AZURE_PUBLIC_CLOUD,
28//! )
29//! .await?;
30//! Ok(())
31//! }
32//! ```
33//!
34//! You can learn more about this authorization flow [here](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow#third-case-access-token-request-with-a-federated-credential).
35
36mod login_response;
37
38use azure_core::{
39 content_type,
40 error::{ErrorKind, ResultExt},
41 headers, HttpClient, Method, Request, Url,
42};
43use login_response::LoginResponse;
44use std::sync::Arc;
45use tracing::{debug, error};
46use url::form_urlencoded;
47
48/// Perform the client credentials flow
49pub async fn perform(
50 http_client: Arc<dyn HttpClient>,
51 client_id: &str,
52 client_assertion: &str,
53 scopes: &[&str],
54 tenant_id: &str,
55 host: &Url,
56) -> azure_core::Result<LoginResponse> {
57 let encoded: String = form_urlencoded::Serializer::new(String::new())
58 .append_pair("client_id", client_id)
59 .append_pair("scope", &scopes.join(" "))
60 .append_pair(
61 "client_assertion_type",
62 "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
63 )
64 .append_pair("client_assertion", client_assertion)
65 .append_pair("grant_type", "client_credentials")
66 .finish();
67
68 let url = host
69 .join(&format!("/{tenant_id}/oauth2/v2.0/token"))
70 .with_context(ErrorKind::DataConversion, || {
71 format!("The supplied tenant id could not be url encoded: {tenant_id}")
72 })?;
73
74 let mut req = Request::new(url, Method::Post);
75 req.insert_header(
76 headers::CONTENT_TYPE,
77 content_type::APPLICATION_X_WWW_FORM_URLENCODED,
78 );
79 req.set_body(encoded);
80 let rsp = http_client.execute_request(&req).await?;
81 let rsp_status = rsp.status();
82 debug!("rsp_status == {:?}", rsp_status);
83 if rsp_status.is_success() {
84 rsp.json().await
85 } else {
86 let (rsp_status, rsp_headers, rsp_body) = rsp.deconstruct();
87 let rsp_body = rsp_body.collect().await?;
88 let text = std::str::from_utf8(&rsp_body)?;
89 error!("rsp_body == {:?}", text);
90 Err(ErrorKind::http_response_from_parts(rsp_status, &rsp_headers, &rsp_body).into_error())
91 }
92}