azure_identity/token_credentials/
options.rs

1use crate::env::Env;
2use azure_core::error::{ErrorKind, ResultExt};
3use std::sync::Arc;
4use url::Url;
5
6const AZURE_AUTHORITY_HOST_ENV_KEY: &str = "AZURE_AUTHORITY_HOST";
7const AZURE_PUBLIC_CLOUD: &str = "https://login.microsoftonline.com";
8
9/// Provides options to configure how the Identity library makes authentication
10/// requests to Azure Active Directory.
11#[derive(Debug, Clone)]
12pub struct TokenCredentialOptions {
13    env: Env,
14    http_client: Arc<dyn azure_core::HttpClient>,
15    authority_host: String,
16}
17
18/// The default token credential options.
19/// The authority host is taken from the `AZURE_AUTHORITY_HOST` environment variable if set and a valid URL.
20/// If not, the default authority host is `https://login.microsoftonline.com` for the Azure public cloud.
21impl Default for TokenCredentialOptions {
22    fn default() -> Self {
23        let env = Env::default();
24        let authority_host = env
25            .var(AZURE_AUTHORITY_HOST_ENV_KEY)
26            .unwrap_or_else(|_| AZURE_PUBLIC_CLOUD.to_owned());
27        Self {
28            env: Env::default(),
29            http_client: azure_core::new_http_client(),
30            authority_host,
31        }
32    }
33}
34
35impl TokenCredentialOptions {
36    #[cfg(test)]
37    pub(crate) fn new(env: Env, http_client: Arc<dyn azure_core::HttpClient>) -> Self {
38        Self {
39            env,
40            http_client,
41            authority_host: AZURE_PUBLIC_CLOUD.to_owned(),
42        }
43    }
44    /// Set the authority host for authentication requests.
45    pub fn set_authority_host(&mut self, authority_host: String) {
46        self.authority_host = authority_host;
47    }
48
49    /// The authority host to use for authentication requests.  The default is
50    /// `https://login.microsoftonline.com`.
51    pub fn authority_host(&self) -> azure_core::Result<Url> {
52        Url::parse(&self.authority_host).with_context(ErrorKind::DataConversion, || {
53            format!("invalid authority host URL {}", &self.authority_host)
54        })
55    }
56
57    pub fn http_client(&self) -> Arc<dyn azure_core::HttpClient> {
58        self.http_client.clone()
59    }
60
61    pub(crate) fn env(&self) -> &Env {
62        &self.env
63    }
64}
65
66impl From<Arc<dyn azure_core::HttpClient>> for TokenCredentialOptions {
67    fn from(http_client: Arc<dyn azure_core::HttpClient>) -> Self {
68        Self {
69            http_client,
70            ..Default::default()
71        }
72    }
73}