Skip to content

Commit 1c007f0

Browse files
alexwolfmsftchristothesscottaddie
authored
New auth best practices doc (#44284)
* New auth best practices doc --------- Co-authored-by: Christopher Scott <[email protected]> Co-authored-by: Scott Addie <[email protected]>
1 parent 0490d52 commit 1c007f0

File tree

8 files changed

+204
-1
lines changed

8 files changed

+204
-1
lines changed

docs/azure/TOC.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@
7575
href: ./sdk/authentication/additional-methods.md
7676
- name: Credential chains
7777
href: ./sdk/authentication/credential-chains.md
78+
- name: Best practices
79+
href: ./sdk/authentication/authentication-best-practices.md
7880
- name: ASP.NET Core guidance
7981
href: ./sdk/aspnetcore-guidance.md
8082
- name: Resource management
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
---
2+
title: Authentication best practices with the Azure Identity library for .NET
3+
description: This article describes authentication best practices to follow when using the Azure Identity library for .NET.
4+
ms.topic: conceptual
5+
ms.date: 01/15/2025
6+
---
7+
8+
# Authentication best practices with the Azure Identity library for .NET
9+
10+
This article offers guidelines to help you maximize the performance and reliability of your .NET apps when authenticating to Azure services. To make the most of the Azure Identity library for .NET, it's important to understand potential issues and mitigation techniques.
11+
12+
## Use deterministic credentials in production environments
13+
14+
[`DefaultAzureCredential`](/dotnet/azure/sdk/authentication/credential-chains?tabs=dac#defaultazurecredential-overview) is the most approachable way to get started with the Azure Identity library, but that convenience also introduces certain tradeoffs. Most notably, the specific credential in the chain that will succeed and be used for request authentication can't be guaranteed ahead of time. In a production environment, this unpredictability can introduce significant and sometimes subtle problems.
15+
16+
For example, consider the following hypothetical sequence of events:
17+
18+
1. An organization's security team mandates all apps use managed identity to authenticate to Azure resources.
19+
1. For months, a .NET app hosted on an Azure Virtual Machine (VM) successfully uses `DefaultAzureCredential` to authenticate via managed identity.
20+
1. Without telling the support team, a developer installs the Azure CLI on that VM and runs the `az login` command to authenticate to Azure.
21+
1. Due to a separate configuration change in the Azure environment, authentication via the original managed identity unexpectedly begins to fail silently.
22+
1. `DefaultAzureCredential` skips the failed `ManagedIdentityCredential` and searches for the next available credential, which is `AzureCliCredential`.
23+
1. The application starts utilizing the Azure CLI credentials rather than the managed identity, which may fail or result in unexpected elevation or reduction of privileges.
24+
25+
To prevent these types of subtle issues or silent failures in production apps, strongly consider moving from `DefaultAzureCredential` to one of the following deterministic solutions:
26+
27+
- 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.
28+
- A pared-down `ChainedTokenCredential` implementation optimized for the Azure environment in which your app runs. `ChainedTokenCredential` essentially creates a specific allow-list of acceptable credential options, such as `ManagedIdentity` for production and `VisualStudioCredential` for development.
29+
30+
For example, consider the following `DefaultAzureCredential` configuration in an ASP.NET Core project:
31+
32+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_Dac" highlight="6,7":::
33+
34+
Replace the preceding code with a `ChainedTokenCredential` implementation that specifies only the necessary credentials:
35+
36+
:::code language="csharp" source="../snippets/authentication/credential-chains/Program.cs" id="snippet_Ctc" highlight="6-8":::
37+
38+
In this example, `ManagedIdentityCredential` would be automatically discovered in production, while `VisualStudioCredential` would work in local development environments.
39+
40+
## Reuse credential instances
41+
42+
Reuse credential instances when possible to improve app resilience and reduce the number of access token requests issued to Microsoft Entra ID. When a credential is reused, an attempt is made to fetch a token from the app token cache managed by the underlying MSAL dependency. For more information, see [Token caching in the Azure Identity client library](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/samples/TokenCache.md).
43+
44+
> [!IMPORTANT]
45+
> A high-volume app that doesn't reuse credentials may encounter HTTP 429 throttling responses from Microsoft Entra ID, which can lead to app outages.
46+
47+
The recommended credential reuse strategy differs by .NET application type.
48+
49+
# [ASP.NET Core](#tab/aspdotnet)
50+
51+
Implement credential reuse through the `UseCredential` method of `Microsoft.Extensions.Azure`:
52+
53+
:::code language="csharp" source="../snippets/authentication/best-practices/Program.cs" id="snippet_credential_reuse_Dac" highlight="6" :::
54+
55+
For information on this approach, see [Authenticate using Microsoft Entra ID](/dotnet/azure/sdk/aspnetcore-guidance?tabs=api#authenticate-using-microsoft-entra-id).
56+
57+
# [Other](#tab/other)
58+
59+
:::code language="csharp" source="../snippets/authentication/best-practices/Program.cs" id="snippet_credential_reuse_noDac" highlight="8, 12" :::
60+
61+
---
62+
63+
## Understand the managed identity retry strategy
64+
65+
The Azure Identity library for .NET allows you to authenticate via managed identity with `ManagedIdentityCredential`. The way in which you use `ManagedIdentityCredential` impacts the applied retry strategy. When used via:
66+
67+
- `DefaultAzureCredential`, no retries are attempted when the initial token acquisition attempt fails or times out after a short duration. This is the least resilient option because it is optimized to "fail fast" for an efficient development inner-loop.
68+
- Any other approach, such as `ChainedTokenCredential` or `ManagedIdentityCredential` directly:
69+
- The time interval between retries starts at 0.8 seconds, and a maximum of five retries are attempted, by default. This option is optimized for resilience but introduces potentially unwanted delays in the development inner-loop.
70+
- To change any of the default retry settings, use the `Retry` property on `ManagedIdentityCredentialOptions`. For example, retry a maximum of three times, with a starting interval of 0.5 seconds:
71+
72+
:::code language="csharp" source="../snippets/authentication/best-practices/Program.cs" id="snippet_retries" highlight="5-9" :::
73+
74+
For more information on customizing retry policies, see [Setting a custom retry policy](https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/Configuration.md#setting-a-custom-retry-policy).

docs/azure/sdk/snippets/authentication/Directory.Packages.props

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
</PropertyGroup>
55
<ItemGroup>
66
<!-- Azure SDK packages -->
7+
<PackageVersion Include="Microsoft.Extensions.Azure" Version="1.7.5" />
78
<PackageVersion Include="Azure.Identity" Version="1.13.1" />
89
<PackageVersion Include="Azure.Identity.Broker" Version="1.1.0" />
10+
<PackageVersion Include="Azure.Security.KeyVault.Secrets" Version="4.7.0" />
911
<PackageVersion Include="Azure.Storage.Blobs" Version="12.21.2" />
10-
<PackageVersion Include="Microsoft.Extensions.Azure" Version="1.7.5" />
1112

1213
<!-- ASP.NET Core packages -->
1314
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net9.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Azure.Identity" />
11+
<PackageReference Include="Azure.Security.KeyVault.Secrets" />
12+
<PackageReference Include="Azure.Storage.Blobs" />
13+
<PackageReference Include="Microsoft.Extensions.Azure"/>
14+
</ItemGroup>
15+
16+
</Project>
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
using Azure.Identity;
2+
using Azure.Security.KeyVault.Secrets;
3+
using Azure.Storage.Blobs;
4+
using Microsoft.Extensions.Azure;
5+
6+
var userAssignedClientId = "<user-assigned-client-id>";
7+
var builder = WebApplication.CreateBuilder(args);
8+
9+
#region snippet_credential_reuse_Dac
10+
builder.Services.AddAzureClients(clientBuilder =>
11+
{
12+
clientBuilder.AddSecretClient(new Uri("<key-vault-url>"));
13+
clientBuilder.AddBlobServiceClient(new Uri("<blob-storage-uri>"));
14+
15+
clientBuilder.UseCredential(new DefaultAzureCredential());
16+
});
17+
#endregion snippet_credential_reuse_Dac
18+
19+
#region snippet_credential_reuse_noDac
20+
ChainedTokenCredential credentialChain = new(
21+
new ManagedIdentityCredential(
22+
ManagedIdentityId.FromUserAssignedClientId(userAssignedClientId)),
23+
new VisualStudioCredential());
24+
25+
BlobServiceClient blobServiceClient = new(
26+
new Uri("<blob-storage-uri>"),
27+
credentialChain);
28+
29+
SecretClient secretClient = new(
30+
new Uri("<key-vault-url>"),
31+
credentialChain);
32+
#endregion snippet_credential_reuse_noDac
33+
34+
#region snippet_retries
35+
ManagedIdentityCredentialOptions miCredentialOptions = new(
36+
ManagedIdentityId.FromUserAssignedClientId(userAssignedClientId)
37+
)
38+
{
39+
Retry =
40+
{
41+
MaxRetries = 3,
42+
Delay = TimeSpan.FromSeconds(0.5),
43+
}
44+
};
45+
ChainedTokenCredential tokenChain = new(
46+
new ManagedIdentityCredential(miCredentialOptions),
47+
new VisualStudioCredential()
48+
);
49+
#endregion
50+
51+
builder.Services.AddEndpointsApiExplorer();
52+
53+
var app = builder.Build();
54+
55+
app.UseHttpsRedirection();
56+
57+
var summaries = new[]
58+
{
59+
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
60+
};
61+
62+
app.MapGet("/weatherforecast", () =>
63+
{
64+
var forecast = Enumerable.Range(1, 5).Select(index =>
65+
new WeatherForecast
66+
(
67+
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
68+
Random.Shared.Next(-20, 55),
69+
summaries[Random.Shared.Next(summaries.Length)]
70+
))
71+
.ToArray();
72+
return forecast;
73+
})
74+
.WithName("GetWeatherForecast");
75+
76+
app.Run();
77+
78+
internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
79+
{
80+
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
81+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"profiles": {
3+
"AuthBestPractices": {
4+
"commandName": "Project",
5+
"launchBrowser": true,
6+
"environmentVariables": {
7+
"ASPNETCORE_ENVIRONMENT": "Development"
8+
},
9+
"applicationUrl": "https://localhost:56902;http://localhost:56903"
10+
}
11+
}
12+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
}
8+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"LogLevel": {
4+
"Default": "Information",
5+
"Microsoft.AspNetCore": "Warning"
6+
}
7+
},
8+
"AllowedHosts": "*"
9+
}

0 commit comments

Comments
 (0)