Skip to content

Commit 6ff3538

Browse files
Add Azure Identity library credential chains doc (#42049)
* Add Azure Identity library credential chains doc * Update mermaid diagrams * Fix code snippets * Add H1 * Move sample code * Add 2 more code samples * Edit diagrams * Replace list with table * Rename directory * Tweak wording * Accessibility improvements * Remove unnecessary http file * Add links to credentials * Update diagrams * Update credential name * Edit pass * More edits * Update title * Edit pass * Add sequence diagram * Update benefits * Add metadata to includes * Move mermaid markup files to includes folder * Fix build warnings * Fix lightboxes * Fix images * React to feedback * Add line highlighting * Small edits * Move sample app * Add a debug section * Edits to debug section * More edits to debug section * Fix heading * React to Maor feedback * Add missing tab IDs * Small edit * Link to env vars section in README * Remove lightboxes * React to Bill's feedback * React to David's feedback Co-authored-by: David Pine <[email protected]> * Update docs/azure/sdk/snippets/authentication/credential-chains/Program.cs Co-authored-by: David Pine <[email protected]> * Convert text to note --------- Co-authored-by: David Pine <[email protected]>
1 parent 403bc36 commit 6ff3538

17 files changed

+485
-18
lines changed

docs/azure/TOC.yml

+3-1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@
6767
href: ./sdk/authentication/create-token-credentials-from-configuration.md
6868
- name: Additional auth methods
6969
href: ./sdk/authentication/additional-methods.md
70+
- name: Credential chains
71+
href: ./sdk/authentication/credential-chains.md
7072
- name: Resource management
7173
href: ./sdk/resource-management.md
7274
- name: Dependency injection
@@ -118,4 +120,4 @@
118120
- name: All samples
119121
href: /samples/browse/?languages=csharp%2Caspx-csharp%2Cfsharp%2Cvb
120122
- name: API reference
121-
href: /dotnet/api/overview/azure/?view=azure-dotnet&preserve-view=true
123+
href: /dotnet/api/overview/azure/?view=azure-dotnet&preserve-view=true
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
---
2+
title: 'Credential chains in the Azure Identity library for .NET'
3+
description: 'This article describes the DefaultAzureCredential and ChainedTokenCredential classes in the Azure Identity library.'
4+
ms.topic: conceptual
5+
ms.date: 08/13/2024
6+
---
7+
8+
# Credential chains in the Azure Identity library for .NET
9+
10+
The Azure Identity library provides *credentials*&mdash;public classes derived from the Azure Core library's [TokenCredential](/dotnet/api/azure.core.tokencredential?view=azure-dotnet&preserve-view=true) class. A credential represents a distinct authentication flow for acquiring an access token from Microsoft Entra ID. These credentials can be chained together to form an ordered sequence of authentication mechanisms to be attempted.
11+
12+
## How a chained credential works
13+
14+
At runtime, a credential chain attempts to authenticate using the sequence's first credential. If that credential fails to acquire an access token, the next credential in the sequence is attempted, and so on, until an access token is successfully obtained. The following sequence diagram illustrates this behavior:
15+
16+
:::image type="content" source="../media/mermaidjs/ChainSequence.svg" alt-text="Credential chain sequence diagram":::
17+
18+
## Why use credential chains
19+
20+
A chained credential can offer the following benefits:
21+
22+
- **Environment awareness**: Automatically selects the most appropriate credential based on the environment in which the app is running. Without it, you'd have to write code like this:
23+
24+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_NoChain":::
25+
26+
- **Seamless transitions**: Your app can move from local development to your staging or production environment without changing authentication code.
27+
- **Improved resiliency**: Includes a fallback mechanism that moves to the next credential when the prior fails to acquire an access token.
28+
29+
## How to choose a chained credential
30+
31+
There are two disparate philosophies to credential chaining:
32+
33+
- **"Tear down" a chain**: Start with a preconfigured chain and exclude what you don't need. For this approach, see the [DefaultAzureCredential overview](#defaultazurecredential-overview) section.
34+
- **"Build up" a chain**: Start with an empty chain and include only what you need. For this approach, see the [ChainedTokenCredential overview](#chainedtokencredential-overview) section.
35+
36+
## DefaultAzureCredential overview
37+
38+
[DefaultAzureCredential](/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet&preserve-view=true) is an opinionated, preconfigured chain of credentials. It's designed to support many environments, along with the most common authentication flows and developer tools. In graphical form, the underlying chain looks like this:
39+
40+
:::image type="content" source="../media/mermaidjs/DefaultAzureCredentialAuthFlow.svg" alt-text="DefaultAzureCredential auth flowchart":::
41+
42+
The order in which `DefaultAzureCredential` attempts credentials follows.
43+
44+
| Order | Credential | Description | Enabled by default? |
45+
|-------|---------------------|-------------|---------------------|
46+
| 1 | [Environment][env-cred] |Reads a collection of environment variables to determine if an application service principal (application user) is configured for the app. If so, `DefaultAzureCredential` uses these values to authenticate the app to Azure. This method is most often used in server environments but can also be used when developing locally. | Yes |
47+
| 2 | [Workload Identity][wi-cred] |If the app is deployed to an Azure host with Workload Identity enabled, authenticate that account. | Yes |
48+
| 3 | [Managed Identity][mi-cred] |If the app is deployed to an Azure host with Managed Identity enabled, authenticate the app to Azure using that Managed Identity. | Yes |
49+
| 4 | [Visual Studio][vs-cred] |If the developer authenticated to Azure by logging into Visual Studio, authenticate the app to Azure using that same account. | Yes |
50+
| 5 | [Azure CLI][az-cred] |If the developer authenticated to Azure using Azure CLI's `az login` command, authenticate the app to Azure using that same account. | Yes |
51+
| 6 | [Azure PowerShell][pwsh-cred] |If the developer authenticated to Azure using Azure PowerShell's `Connect-AzAccount` cmdlet, authenticate the app to Azure using that same account. | Yes |
52+
| 7 | [Azure Developer CLI][azd-cred] |If the developer authenticated to Azure using Azure Developer CLI's `azd auth login` command, authenticate with that account. | Yes |
53+
| 8 | [Interactive browser][int-cred] |If enabled, interactively authenticate the developer via the current system's default browser. | No |
54+
55+
[env-cred]: /dotnet/api/azure.identity.environmentcredential?view=azure-dotnet&preserve-view=true
56+
[wi-cred]: /dotnet/api/azure.identity.workloadidentitycredential?view=azure-dotnet&preserve-view=true
57+
[mi-cred]: /dotnet/api/azure.identity.managedidentitycredential?view=azure-dotnet&preserve-view=true
58+
[vs-cred]: /dotnet/api/azure.identity.visualstudiocredential?view=azure-dotnet&preserve-view=true
59+
[az-cred]: /dotnet/api/azure.identity.azureclicredential?view=azure-dotnet&preserve-view=true
60+
[pwsh-cred]: /dotnet/api/azure.identity.azurepowershellcredential?view=azure-dotnet&preserve-view=true
61+
[azd-cred]: /dotnet/api/azure.identity.azuredeveloperclicredential?view=azure-dotnet&preserve-view=true
62+
[int-cred]: /dotnet/api/azure.identity.interactivebrowsercredential?view=azure-dotnet&preserve-view=true
63+
64+
In its simplest form, you can use the parameterless version of `DefaultAzureCredential` as follows:
65+
66+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_Dac":::
67+
68+
### How to customize DefaultAzureCredential
69+
70+
To remove a credential from `DefaultAzureCredential`, use the corresponding `Exclude`-prefixed property in [DefaultAzureCredentialOptions](/dotnet/api/azure.identity.defaultazurecredentialoptions?view=azure-dotnet&preserve-view=true#properties). For example:
71+
72+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_DacExcludes" highlight="4-5":::
73+
74+
In the preceding code sample, `EnvironmentCredential` and `WorkloadIdentityCredential` are removed from the credential chain. As a result, the first credential to be attempted is `ManagedIdentityCredential`. The modified chain looks like this:
75+
76+
:::image type="content" source="../media/mermaidjs/DefaultAzureCredentialExcludes.svg" alt-text="DefaultAzureCredential using Excludes properties":::
77+
78+
> [!NOTE]
79+
> `InteractiveBrowserCredential` is excluded by default and therefore isn't shown in the preceding diagram. To include `InteractiveBrowserCredential`, use constructor <xref:Azure.Identity.DefaultAzureCredential.%23ctor%28System.Boolean%29>.
80+
81+
As more `Exclude`-prefixed properties are set to `true` (credential exclusions are configured), the advantages of using `DefaultAzureCredential` diminish. In such cases, `ChainedTokenCredential` is a better choice and requires less code. To illustrate, these two code samples behave the same way:
82+
83+
### [DefaultAzureCredential](#tab/dac)
84+
85+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_DacEquivalents":::
86+
87+
### [ChainedTokenCredential](#tab/ctc)
88+
89+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_CtcEquivalents":::
90+
91+
---
92+
93+
## ChainedTokenCredential overview
94+
95+
[ChainedTokenCredential](/dotnet/api/azure.identity.chainedtokencredential?view=azure-dotnet&preserve-view=true) is an empty chain to which you add credentials to suit your app's needs. For example:
96+
97+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_Ctc":::
98+
99+
The preceding code sample creates a tailored credential chain comprised of two credentials. The user-assigned managed identity variant of `ManagedIdentityCredential` is attempted first, followed by `VisualStudioCredential`, if necessary. In graphical form, the chain looks like this:
100+
101+
:::image type="content" source="../media/mermaidjs/ChainedTokenCredentialAuthFlow.svg" alt-text="ChainedTokenCredential":::
102+
103+
> [!TIP]
104+
> For improved performance, optimize credential ordering in `ChainedTokenCredential` for your production environment. Credentials intended for use in the local development environment should be added last.
105+
106+
## Usage guidance for DefaultAzureCredential
107+
108+
`DefaultAzureCredential` is undoubtedly the easiest way to get started with the Azure Identity library, but with that convenience comes tradeoffs. Once you deploy your app to Azure, you should understand the app's authentication requirements. For that reason, strongly consider moving from `DefaultAzureCredential` to one of the following solutions:
109+
110+
- A specific `TokenCredential` implementation, such as `ManagedIdentityCredential`. See the [**Derived** list](/dotnet/api/azure.core.tokencredential?view=azure-dotnet&preserve-view=true#definition) for options.
111+
- A pared-down `ChainedTokenCredential` implementation optimized for the Azure environment in which your app runs.
112+
113+
Here's why:
114+
115+
- **Debugging challenges**: When authentication fails, it can be challenging to debug and identify the offending credential. You must enable logging to see the progression from one credential to the next and the success/failure status of each. For more information, see [Debug a chained credential](#debug-a-chained-credential).
116+
- **Performance overhead**: The process of sequentially trying multiple credentials can introduce performance overhead. For example, when running on a local development machine, managed identity is unavailable. Consequently, `ManagedIdentityCredential` always fails in the local development environment, unless explicitly disabled via its corresponding `Exclude`-prefixed property.
117+
- **Unpredictable behavior**: `DefaultAzureCredential` checks for the presence of certain [environment variables](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/README.md#environment-variables). It's possible that someone could add or modify these environment variables at the system level on the host machine. Those changes apply globally and therefore alter the behavior of `DefaultAzureCredential` at runtime in any app running on that machine.
118+
119+
## Debug a chained credential
120+
121+
To diagnose an unexpected issue or to understand what a chained credential is doing, [enable logging](../logging.md) in your app. Optionally, filter the logs to only those events emitted from the Azure Identity library. For example:
122+
123+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_FilteredLogging":::
124+
125+
For illustration purposes, assume the parameterless form of `DefaultAzureCredential` was used to authenticate a request to a Log Analytics workspace. The app ran in the local development environment, and Visual Studio was authenticated to an Azure account. The next time the app ran, the following pertinent entries appeared in the output:
126+
127+
:::code language="output" source="../snippets/authentication/credential-chains/dac-logs.txt":::
128+
129+
In the preceding output, notice that:
130+
131+
- `EnvironmentCredential`, `WorkloadIdentityCredential`, and `ManagedIdentityCredential` each failed to acquire a Microsoft Entra access token, in that order.
132+
- The `DefaultAzureCredential credential selected:`-prefixed entry indicates the credential that was selected&mdash;`VisualStudioCredential` in this case. Since `VisualStudioCredential` succeeded, no credentials beyond it were used.

docs/azure/sdk/authentication/index.md

-17
Original file line numberDiff line numberDiff line change
@@ -62,20 +62,3 @@ When an app is run on a developer's workstation during local development, it mus
6262
## Use DefaultAzureCredential in an application
6363

6464
[!INCLUDE [Implement DefaultAzureCredential](<../includes/implement-defaultazurecredential.md>)]
65-
66-
### Explore the sequence of DefaultAzureCredential authentication methods
67-
68-
Internally, `DefaultAzureCredential` implements a chain of credential providers for authenticating applications to Azure resources. Each credential provider is able to detect if credentials of that type are configured for the app. `DefaultAzureCredential` sequentially checks each provider in order and uses the credentials from the first provider that has credentials configured.
69-
70-
The order and locations in which `DefaultAzureCredential` looks for credentials is found at [DefaultAzureCredential](/dotnet/api/overview/azure/identity-readme?view=azure-dotnet&preserve-view=true#defaultazurecredential).
71-
72-
| Credential type | Description |
73-
|-------------------------------|-------------|
74-
| Environment | `DefaultAzureCredential` reads a set of environment variables to determine if an application service principal (application user) has been set for the app. If so, `DefaultAzureCredential` uses these values to authenticate the app to Azure.<br><br>This method is most often used in server environments but can also be used when developing locally. |
75-
| Workload Identity | If the app is deployed to an Azure host with Workload Identity enabled, `DefaultAzureCredential` will authenticate that account. |
76-
| Managed Identity | If the app is deployed to an Azure host with Managed Identity enabled, `DefaultAzureCredential` will authenticate the app to Azure using that Managed Identity. Authentication using a Managed Identity is discussed in the [Authentication in server environments](#authentication-in-server-environments) section of this document.<br><br>This method is only available when the app is hosted in Azure using a service like Azure App Service, Azure Functions, or Azure Virtual Machines. |
77-
| Visual Studio | If the developer has authenticated to Azure by logging into Visual Studio, `DefaultAzureCredential` will authenticate the app to Azure using that same account. |
78-
| Azure CLI | If the developer has authenticated to Azure using Azure CLI's `az login` command, `DefaultAzureCredential` will authenticate the app to Azure using that same account. |
79-
| Azure PowerShell | If the developer has authenticated to Azure using Azure PowerShell's `Connect-AzAccount` cmdlet, `DefaultAzureCredential` will authenticate the app to Azure using that same account. |
80-
| Azure Developer CLI | If the developer has authenticated to Azure using Azure Developer CLI's `azd auth login` command, `DefaultAzureCredential` will authenticate with that account. |
81-
| Interactive | If enabled, `DefaultAzureCredential` will interactively authenticate the developer via the current system's default browser. By default, this option is disabled. |
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
---
2+
ms.topic: include
3+
ms.date: 08/07/2024
4+
---
5+
6+
```mermaid
7+
%% STEPS TO GENERATE IMAGE
8+
%% =======================
9+
%% 1. Install mermaid CLI v10.9.1 (see https://github.com/mermaid-js/mermaid-cli/blob/master/README.md):
10+
%% npm i -g @mermaid-js/[email protected]
11+
%% 2. Run command: mmdc -i ChainSequence.md -o ../../media/mermaidjs/ChainSequence.svg
12+
13+
sequenceDiagram
14+
autonumber;
15+
16+
participant A as .NET app;
17+
participant B as Credential chain;
18+
participant C as TokenCredential instance;
19+
20+
A->>B: Authenticate to Microsoft Entra ID;
21+
activate B;
22+
B->>B: GetToken;
23+
loop Traverse TokenCredential collection until AccessToken received
24+
B->>C: Fetch token;
25+
activate C;
26+
C->>C: GetToken;
27+
break when Result is AccessToken
28+
C-->>B: Result;
29+
end;
30+
deactivate C;
31+
end;
32+
33+
B-->>A: AccessToken;
34+
deactivate B;
35+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
ms.topic: include
3+
ms.date: 08/07/2024
4+
---
5+
6+
```mermaid
7+
%% STEPS TO GENERATE IMAGE
8+
%% =======================
9+
%% 1. Install mermaid CLI v10.9.1 (see https://github.com/mermaid-js/mermaid-cli/blob/master/README.md):
10+
%% npm i -g @mermaid-js/[email protected]
11+
%% 2. Run command: mmdc -i ChainedTokenCredentialAuthFlow.md -o ../../media/mermaidjs/ChainedTokenCredentialAuthFlow.svg
12+
13+
%%{
14+
init: {
15+
'theme': 'base',
16+
'themeVariables': {
17+
'tertiaryBorderColor': '#fff',
18+
'tertiaryColor': '#fff'
19+
}
20+
}
21+
}%%
22+
23+
flowchart LR;
24+
C(Managed Identity):::deployed --> D(Visual Studio):::developer;
25+
26+
%% Define styles for credential type boxes
27+
classDef deployed fill:#95C37E, stroke:#71AD4C, stroke-width:2px;
28+
classDef developer fill:#F5AF6F, stroke:#EB7C39, stroke-width:2px;
29+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
---
2+
ms.topic: include
3+
ms.date: 08/07/2024
4+
---
5+
6+
```mermaid
7+
%% STEPS TO GENERATE IMAGE
8+
%% =======================
9+
%% 1. Install mermaid CLI v10.9.1 (see https://github.com/mermaid-js/mermaid-cli/blob/master/README.md):
10+
%% npm i -g @mermaid-js/[email protected]
11+
%% 2. Run command: mmdc -i DefaultAzureCredentialAuthFlow.md -o ../../media/mermaidjs/DefaultAzureCredentialAuthFlow.svg
12+
13+
%%{
14+
init: {
15+
'theme': 'base',
16+
'themeVariables': {
17+
'tertiaryBorderColor': '#fff',
18+
'tertiaryColor': '#fff'
19+
}
20+
}
21+
}%%
22+
23+
flowchart LR;
24+
accTitle: DefaultAzureCredential authentication flow;
25+
accDescr: Flowchart showing the credential chain implemented by DefaultAzureCredential;
26+
27+
subgraph CREDENTIAL TYPES;
28+
direction LR;
29+
Deployed(Deployed service):::deployed ~~~ Developer(Developer tool):::developer ~~~ Interactive(Interactive):::interactive;
30+
end;
31+
32+
subgraph CREDENTIALS;
33+
direction LR;
34+
A(Environment):::deployed --> B(Workload Identity):::deployed --> C(Managed Identity):::deployed --> D(Visual Studio):::developer --> E(Azure CLI):::developer --> F(Azure PowerShell):::developer --> G(Azure Developer CLI):::developer --> H(Interactive browser):::interactive;
35+
end;
36+
37+
%% Define styles for credential type boxes
38+
classDef deployed fill:#95C37E, stroke:#71AD4C, stroke-width:2px;
39+
classDef developer fill:#F5AF6F, stroke:#EB7C39, stroke-width:2px;
40+
classDef interactive fill:#A5A5A5, stroke:#828282, stroke-dasharray:5 5, stroke-width:2px;
41+
42+
%% Add API ref links to credential type boxes
43+
click A "https://learn.microsoft.com/dotnet/api/azure.identity.environmentcredential?view=azure-dotnet" _blank;
44+
click B "https://learn.microsoft.com/dotnet/api/azure.identity.workloadidentitycredential?view=azure-dotnet" _blank;
45+
click C "https://learn.microsoft.com/dotnet/api/azure.identity.managedidentitycredential?view=azure-dotnet" _blank;
46+
click D "https://learn.microsoft.com/dotnet/api/azure.identity.visualstudiocredential?view=azure-dotnet" _blank;
47+
click E "https://learn.microsoft.com/dotnet/api/azure.identity.azureclicredential?view=azure-dotnet" _blank;
48+
click F "https://learn.microsoft.com/dotnet/api/azure.identity.azurepowershellcredential?view=azure-dotnet" _blank;
49+
click G "https://learn.microsoft.com/dotnet/api/azure.identity.azuredeveloperclicredential?view=azure-dotnet" _blank
50+
click H "https://learn.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential?view=azure-dotnet" _blank;
51+
```

0 commit comments

Comments
 (0)