Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updates to the azure_identity README #1990

Merged
merged 18 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
270bb51
Initial pass
ronniegeraghty Dec 21, 2024
60022d3
changed TokenCredential link
ronniegeraghty Dec 21, 2024
91015d9
Fixed code block formatting for install command
ronniegeraghty Dec 21, 2024
7b9dcd7
First draft of identity beta README
ronniegeraghty Jan 14, 2025
1d0c0b8
Refactor README.md to improve link formatting and consistency
ronniegeraghty Jan 28, 2025
573d73a
Clarify version behavior of DefaultAzureCredential and removed commen…
ronniegeraghty Jan 28, 2025
93393c7
Update README.md example to use proper error handling in DefaultAzure…
ronniegeraghty Jan 28, 2025
6c69f2a
Removed commented out sections
ronniegeraghty Jan 28, 2025
b1c1aee
Update README.md example to use SecretClient instead of CosmosClient
ronniegeraghty Jan 29, 2025
17b2c81
Add azure_security_keyvault_secrets as a dev dependency and update RE…
ronniegeraghty Jan 30, 2025
cd238e7
Merge branch 'main' of https://github.com/Azure/azure-sdk-for-rust in…
ronniegeraghty Jan 30, 2025
bf88d02
Add azure_security_keyvault_secrets as a dependency and update README
ronniegeraghty Jan 30, 2025
b6c8cd8
Update README to demonstrate authentication with SecretClient from az…
ronniegeraghty Jan 31, 2025
bb03af4
Fix README example to use correct Key Vault URL format
ronniegeraghty Jan 31, 2025
d312f0c
Update sdk/identity/azure_identity/README.md
ronniegeraghty Feb 3, 2025
e4e5307
Update README to reflect version change for DefaultAzureCredential be…
ronniegeraghty Feb 3, 2025
5c71605
Clarify continuation policy for DefaultAzureCredential in README
ronniegeraghty Feb 4, 2025
53fa6b5
Fixed links to point to existing or future Rust library reference docs.
ronniegeraghty Feb 4, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions sdk/identity/azure_identity/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ async-process.workspace = true
tz-rs = { workspace = true, optional = true }

[dev-dependencies]
azure_security_keyvault_secrets = { path = "../../keyvault/azure_security_keyvault_secrets" }
reqwest.workspace = true
tokio.workspace = true
tracing-subscriber.workspace = true
Expand Down
176 changes: 115 additions & 61 deletions sdk/identity/azure_identity/README.md
Original file line number Diff line number Diff line change
@@ -1,77 +1,131 @@
# azure_identity
# Azure Identity client library for Rust

Azure Identity crate for the unofficial Microsoft Azure SDK for Rust. This crate is part of a collection of crates: for more information please refer to <https://github.com/Azure/azure-sdk-for-rust>.
The Azure Identity library provides [Microsoft Entra ID](https://learn.microsoft.com/entra/fundamentals/whatis) ([formerly Azure Active Directory](https://learn.microsoft.com/entra/fundamentals/new-name)) token authentication support across the Azure SDK. It provides a set of [`TokenCredential`][token_cred_ref] implementations that can be used to construct Azure SDK clients that support Microsoft Entra token authentication.

This crate provides several implementations of the [azure_core::auth::TokenCredential](https://docs.rs/azure_core/latest/azure_core/auth/trait.TokenCredential.html) trait.
It is recommended to start with `azure_identity::create_credential()?`, which will create an instance of `DefaultAzureCredential` by default. If you want to use a specific credential type, the `AZURE_CREDENTIAL_KIND` environment variable may be set to a value from `azure_credential_kinds`, such as `azurecli` or `virtualmachine`.
[Source code] | [Package (crates.io)] | [API reference documentation] | [Microsoft Entra ID documentation]

```rust,no_run
use azure_core::credentials::TokenCredential;
use std::sync::Arc;
## Getting started

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let subscription_id =
std::env::var("AZURE_SUBSCRIPTION_ID").expect("AZURE_SUBSCRIPTION_ID required");
### Install the package

let credential: Arc<dyn TokenCredential> = azure_identity::DefaultAzureCredential::new()?;
Install the Azure Identity library for Rust with cargo:

// Let's enumerate the Azure storage accounts in the subscription using the REST API directly.
// This is just an example. It is easier to use the Azure SDK for Rust crates.
let url = url::Url::parse(&format!("https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01"))?;
```bash
cargo add azure_identity
```

let access_token = credential
.get_token(&["https://management.azure.com/.default"])
.await?;
### Prerequisites

let response = reqwest::Client::new()
.get(url)
.header(
"Authorization",
format!("Bearer {}", access_token.token.secret()),
)
.send()
.await?
.text()
.await?;
* An [Azure subscription].
* The [Azure CLI] can also be useful for authenticating in a development environment, creating accounts, and managing account roles.

println!("{response}");
Ok(())
}
```
### Authenticate during local development

When debugging and executing code locally, it's typical for developers to use their own accounts for authenticating calls to Azure services. The Azure Identity library supports authenticating through developer tools to simplify local development.

#### Authenticate via the Azure CLI

`DefaultAzureCredential` and `AzureCliCredential` can authenticate as the user signed in to the [Azure CLI]. To sign in to the Azure CLI, run `az login`. On a system with a default web browser, the Azure CLI launches the browser to authenticate a user.

When no default browser is available, `az login` uses the device code authentication flow. This flow can also be selected manually by running `az login --use-device-code`.

## Key concepts

### Credentials

A credential is a class that contains or can obtain the data needed for a service client to authenticate requests. Service clients across the Azure SDK accept a credential instance when they're constructed, and use that credential to authenticate requests.

## Design
The Azure Identity library focuses on OAuth authentication with Microsoft Entra ID. It offers various credential classes capable of acquiring a Microsoft Entra access token. See the [Credential classes](#credential-classes "Credential classes") section for a list of this library's credential classes.

Each `TokenCredential` implementation provides a `new` constructor that returns an `azure_core::Result<Arc<Self>>`. The credential provider is contained within an `Arc` because these are designed to be reused by multiple clients for efficiency e.g.:
### DefaultAzureCredential

`DefaultAzureCredential` simplifies authentication while developing apps that deploy to Azure by combining credentials used in Azure hosting environments with credentials used in local development.

#### Continuation policy

`DefaultAzureCredential` attempts to authenticate with all developer credentials until one succeeds, regardless of any errors previous developer credentials experienced. For example, a developer credential may attempt to get a token and fail, so `DefaultAzureCredential` will continue to the next credential in the flow. Deployed service credentials stop the flow with a thrown exception if they're able to attempt token retrieval, but don't receive one.

This allows for trying all of the developer credentials on your machine while having predictable deployed behavior.

## Examples

The following examples are provided:
<!-- no toc -->
* [Authenticate with DefaultAzureCredential](#authenticate-with-defaultazurecredential "Authenticate with DefaultAzureCredential")

### Authenticate with `DefaultAzureCredential`

More details on configuring your environment to use `DefaultAzureCredential` can be found in the class's [reference documentation][default_cred_ref].

This example demonstrates authenticating the `SecretClient` from the [azure_security_keyvault_secrets] crate using `DefaultAzureCredential`.

```rust
use azure_core::credentials::TokenCredential;
use azure_identity::DefaultAzureCredential;
# use azure_core::{ClientOptions, Result};
# use std::sync::Arc;
# struct StorageAccountClient;
# impl StorageAccountClient {
# fn new(_endpoint: &str, _credential: Arc<dyn TokenCredential>, _options: Option<ClientOptions>) -> Result<Arc<Self>> {
# Ok(Arc::new(StorageAccountClient))
# }
# }
# struct SecretClient;
# impl SecretClient {
# fn new(_endpoint: &str, _credential: Arc<dyn TokenCredential>, _options: Option<ClientOptions>) -> Result<Arc<Self>> {
# Ok(Arc::new(SecretClient))
# }
# }

let credential = DefaultAzureCredential::new().unwrap();
let storage_client = StorageAccountClient::new(
"https://myaccount.blob.storage.azure.net",
credential.clone(),
None,
);
let secret_client = SecretClient::new("https://myvault.keyvault.azure.net",
credential.clone(),
None,
);
use azure_security_keyvault_secrets::SecretClient;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let credential = DefaultAzureCredential::new()?;
let client = SecretClient::new("https://your-key-vault-name.vault.azure.net/", credential.clone(), None)?;
Ok(())
}
```

Credentials are cached in memory and refreshed as needed. Using the same credentials in multiple clients prevents authenticating and refreshing tokens numerous times for each client otherwise.
## Credential classes

### Credential chains

|Credential|Usage
|-|-
|[`DefaultAzureCredential`][default_cred_ref]| Provides a simplified authentication experience to quickly start developing applications run in Azure.

### Authenticate Azure-hosted applications

|Credential|Usage
|-|-
|[`ImdsManagedIdentityCredential`][managed_id_cred_ref]| Authenticates the managed identity of an Azure resource.
|[`WorkloadIdentityCredential`][workload_id_cred_ref]| Supports [Microsoft Entra Workload ID](https://learn.microsoft.com/azure/aks/workload-identity-overview) on Kubernetes.

### Authenticate service principals

|Credential|Usage|Reference
|-|-|-
|[`ClientCertificateCredential`][cert_cred_ref]| Authenticates a service principal using a certificate. | [Service principal authentication](https://learn.microsoft.com/entra/identity-platform/app-objects-and-service-principals)

### Authenticate via development tools

|Credential|Usage|Reference
|-|-|-
|[`AzureCliCredential`][cli_cred_ref]| Authenticates in a development environment with the Azure CLI. | [Azure CLI authentication](https://learn.microsoft.com/cli/azure/authenticate-azure-cli)

## Next steps

### Client library support

Client and management libraries listed on the [Azure SDK release page](https://azure.github.io/azure-sdk/releases/latest/rust.html)that support Microsoft Entra authentication accept credentials from this library. You can learn more about using these libraries in their documentation, which is available at [Docs.rs](https://Docs.rs).

### Provide feedback

If you encounter bugs or have suggestions, [open an issue](https://github.com/Azure/azure-sdk-for-rust/issues).

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [https://cla.microsoft.com](https://cla.microsoft.com).

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You'll only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information, see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.

<!-- LINKS -->
[Azure CLI]: https://learn.microsoft.com/cli/azure
[azure_security_keyvault_secrets]: https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/keyvault/azure_security_keyvault_secrets
[Azure subscription]: https://azure.microsoft.com/free/
[cert_cred_ref]: https://docs.rs/azure_identity/latest/azure_identity/struct.ClientCertificateCredential.html
[cli_cred_ref]: https://docs.rs/azure_identity/latest/azure_identity/struct.AzureauthCliCredential.html
[default_cred_ref]: https://docs.rs/azure_identity/latest/azure_identity/struct.DefaultAzureCredential.html
[Microsoft Entra ID documentation]: https://learn.microsoft.com/entra/identity/
[API reference documentation]: https://docs.rs/azure_identity/latest/azure_identity/
[managed_id_cred_ref]: https://docs.rs/azure_identity/latest/azure_identity/struct.ImdsManagedIdentityCredential.html
[Package (crates.io)]: https://crates.io/crates/azure_identity
[Source code]: https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/identity/azure_identity
[token_cred_ref]: https://docs.rs/azure_core/latest/azure_core/struct.TokenCredential.html
[workload_id_cred_ref]: https://docs.rs/azure_identity/latest/azure_identity/struct.WorkloadIdentityCredential.html