The Azure Identity library provides Microsoft Entra ID (formerly Azure Active Directory) token authentication support across the Azure SDK. It provides a set of TokenCredential
implementations that can be used to construct Azure SDK clients that support Microsoft Entra token authentication.
Source code | Package (NuGet) | API reference documentation | Microsoft Entra ID documentation
Install the Azure Identity client library for .NET with NuGet:
dotnet add package Azure.Identity
- An Azure subscription.
- The Azure CLI can also be useful for authenticating in a development environment, creating accounts, and managing account roles.
When debugging and executing code locally, it's typical for a developer to use their own account for authenticating calls to Azure services. There are several developer tools that can be used to perform this authentication in your development environment.
Developers using Visual Studio 2017 or later can authenticate a Microsoft Entra account through the IDE. Apps using DefaultAzureCredential
or VisualStudioCredential
can then use this account to authenticate calls in their app when running locally.
To authenticate in Visual Studio, select the Tools > Options menu to launch the Options dialog. Then navigate to the Azure Service Authentication options to sign in with your Microsoft Entra account.
Developers using Visual Studio Code can use the Azure Account extension to authenticate via the editor. Apps using DefaultAzureCredential
or VisualStudioCodeCredential
can then use this account to authenticate calls in their app when running locally.
It's a known issue that VisualStudioCodeCredential
doesn't work with Azure Account extension versions newer than 0.9.11. A long-term fix to this problem is in progress. In the meantime, authenticate via the Azure CLI.
Developers coding outside of an IDE can also use the Azure CLI to authenticate. Apps using DefaultAzureCredential
or AzureCliCredential
can then use this account to authenticate calls in their app when running locally.
To authenticate with the Azure CLI, run the command az login
. For users running on a system with a default web browser, the Azure CLI launches the browser to authenticate the user.
For systems without a default web browser, the az login
command uses the device code authentication flow. The user can also force the Azure CLI to use the device code flow rather than launching a browser by specifying the --use-device-code
argument.
Developers coding outside of an IDE can also use the Azure Developer CLI to authenticate. Apps using DefaultAzureCredential
or AzureDeveloperCliCredential
can then use this account to authenticate calls in their app when running locally.
To authenticate with the Azure Developer CLI, run the command azd auth login
. For users running on a system with a default web browser, the Azure Developer CLI launches the browser to authenticate the user. For systems without a default web browser, the azd auth login --use-device-code
command uses the device code authentication flow.
Developers coding outside of an IDE can also use Azure PowerShell to authenticate. Apps using DefaultAzureCredential
or AzurePowerShellCredential
can then use this account to authenticate calls in their app when running locally.
To authenticate with Azure PowerShell, run the command Connect-AzAccount
. For users running on a system with a default web browser and version 5.0.0 or later of Azure PowerShell, it launches the browser to authenticate the user. For systems without a default web browser, the Connect-AzAccount
command uses the device code authentication flow. The user can also force Azure PowerShell to use the device code flow rather than launching a browser by specifying the UseDeviceAuthentication
argument.
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 credentials when they're constructed. Service clients use those credentials to authenticate requests to the service.
The Azure Identity library focuses on OAuth authentication with Microsoft Entra ID. It offers numerous credentials capable of acquiring a Microsoft Entra token to authenticate service requests. Each credential in this library is an implementation of the TokenCredential
abstract class in Azure.Core, and any of them can be used to construct service clients capable of authenticating with a TokenCredential
.
See Credential classes for a complete listing of available credential types.
DefaultAzureCredential
simplifies authentication while developing apps that deploy to Azure by combining credentials used in Azure hosting environments with credentials used in local development. For more information, see DefaultAzureCredential overview.
As of version 1.10.1, DefaultAzureCredential
attempts to authenticate with all developer tool credentials until one succeeds, regardless of any errors previous developer tool credentials experienced. For example, a developer tool 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. Prior to version 1.10.1, developer tool credentials would similarly stop the authentication flow if token retrieval failed.
This behavior allows for trying all of the developer tool credentials on your machine while having predictable deployed behavior.
This example demonstrates authenticating SecretClient
from the Azure.Security.KeyVault.Secrets client library with DefaultAzureCredential
:
// Create a secret client using the DefaultAzureCredential
var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), new DefaultAzureCredential());
Many Azure hosts allow the assignment of a user-assigned managed identity. The following examples demonstrate configuring DefaultAzureCredential
to authenticate a user-assigned managed identity when deployed to an Azure host. The sample code uses the credential to authenticate a BlobClient
from the Azure.Storage.Blobs client library. It also demonstrates how you can specify a user-assigned managed identity either by a client ID or a resource ID.
To use a client ID, take one of the following approaches:
- Set the DefaultAzureCredentialOptions.ManagedIdentityClientId property. For example:
// When deployed to an Azure host, DefaultAzureCredential will authenticate the specified user-assigned managed identity.
string userAssignedClientId = "<your managed identity client ID>";
var credential = new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = userAssignedClientId
});
var blobClient = new BlobClient(
new Uri("https://myaccount.blob.core.windows.net/mycontainer/myblob"),
credential);
- Set the
AZURE_CLIENT_ID
environment variable.
To use a resource ID, set the DefaultAzureCredentialOptions.ManagedIdentityResourceId property. The resource ID takes the form /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}
. Because resource IDs can be built by convention, they can be more convenient when there are a large number of user-assigned managed identities in your environment. For example:
string userAssignedResourceId = "<your managed identity resource ID>";
var credential = new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityResourceId = new ResourceIdentifier(userAssignedResourceId)
});
var blobClient = new BlobClient(
new Uri("https://myaccount.blob.core.windows.net/mycontainer/myblob"),
credential);
While DefaultAzureCredential
is generally the quickest way to authenticate apps for Azure, you can create a customized chain of credentials to be considered. ChainedTokenCredential
enables users to combine multiple credential instances to define a customized chain of credentials. For more information, see ChainedTokenCredential overview.
Managed identity authentication is supported either indirectly via DefaultAzureCredential
or directly via ManagedIdentityCredential
for the following Azure services:
- Azure App Service and Azure Functions
- Azure Arc
- Azure Cloud Shell
- Azure Kubernetes Service
- Azure Service Fabric
- Azure Virtual Machines
- Azure Virtual Machines Scale Sets
As of version 1.8.0, ManagedIdentityCredential
supports token caching.
These examples demonstrate authenticating SecretClient
from the Azure.Security.KeyVault.Secrets client library with ManagedIdentityCredential
.
var credential = new ManagedIdentityCredential(clientId: userAssignedClientId);
var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), credential);
var credential = new ManagedIdentityCredential();
var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), credential);
By default, credentials authenticate to the Microsoft Entra endpoint for the Azure Public Cloud. To access resources in other clouds, such as Azure US Government or a private cloud, configure credentials with the AuthorityHost
option. AzureAuthorityHosts defines authorities for well-known clouds:
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzureGovernment });
Not all credentials require this configuration. Credentials that authenticate through a developer tool, such as AzureCliCredential
, use that tool's configuration.
Credential | Usage | Reference |
---|---|---|
DefaultAzureCredential |
Provides a simplified authentication experience to quickly start developing apps run in Azure. | DefaultAzureCredential overview |
ChainedTokenCredential |
Allows users to define custom authentication flows comprised of multiple credentials. | ChainedTokenCredential overview |
Credential | Usage |
---|---|
EnvironmentCredential |
Authenticates a service principal or user via credential information specified in environment variables. |
ManagedIdentityCredential |
Authenticates the managed identity of an Azure resource. |
WorkloadIdentityCredential |
Supports Microsoft Entra Workload ID on Kubernetes. |
Credential | Usage | Reference |
---|---|---|
AzurePipelinesCredential |
Supports Microsoft Entra Workload ID on Azure Pipelines. | example |
ClientAssertionCredential |
Authenticates a service principal using a signed client assertion. | |
ClientCertificateCredential |
Authenticates a service principal using a certificate. | Service principal authentication |
ClientSecretCredential |
Authenticates a service principal using a secret. | Service principal authentication |
Credential | Usage | Reference |
---|---|---|
AuthorizationCodeCredential |
Authenticates a user with a previously obtained authorization code. | OAuth2 authentication code |
DeviceCodeCredential |
Interactively authenticates a user on devices with limited UI. | Device code authentication |
InteractiveBrowserCredential |
Interactively authenticates a user with the default system browser. | OAuth2 authentication code |
OnBehalfOfCredential |
Propagates the delegated user identity and permissions through the request chain. | On-behalf-of authentication |
UsernamePasswordCredential |
Authenticates a user with a username and password. | Username + password authentication |
Credential | Usage | Reference |
---|---|---|
AzureCliCredential |
Authenticates in a development environment with the Azure CLI. | Azure CLI authentication |
AzureDeveloperCliCredential |
Authenticates in a development environment with the Azure Developer CLI. | Azure Developer CLI Reference |
AzurePowerShellCredential |
Authenticates in a development environment with the Azure PowerShell. | Azure PowerShell authentication |
VisualStudioCredential |
Authenticates in a development environment with Visual Studio. | Visual Studio configuration |
VisualStudioCodeCredential |
Authenticates as the user signed in to the Visual Studio Code Azure Account extension. | VS Code Azure Account extension |
Note: All credential implementations in the Azure Identity library are threadsafe, and a single credential instance can be used by multiple service clients.
DefaultAzureCredential
and EnvironmentCredential
can be configured with environment variables. Each type of authentication requires values for specific variables.
Variable name | Value |
---|---|
AZURE_CLIENT_ID |
ID of a Microsoft Entra application |
AZURE_TENANT_ID |
ID of the application's Microsoft Entra tenant |
AZURE_CLIENT_SECRET |
one of the application's client secrets |
Variable name | Value |
---|---|
AZURE_CLIENT_ID |
ID of a Microsoft Entra application |
AZURE_TENANT_ID |
ID of the application's Microsoft Entra tenant |
AZURE_CLIENT_CERTIFICATE_PATH |
path to a PFX or PEM-encoded certificate file including private key |
AZURE_CLIENT_CERTIFICATE_PASSWORD |
(optional) the password protecting the certificate file (currently only supported for PFX (PKCS12) certificates) |
AZURE_CLIENT_SEND_CERTIFICATE_CHAIN |
(optional) send certificate chain in x5c header to support subject name / issuer based authentication |
Variable name | Value |
---|---|
AZURE_CLIENT_ID |
ID of a Microsoft Entra application |
AZURE_TENANT_ID |
ID of the application's Microsoft Entra tenant |
AZURE_USERNAME |
a username (usually an email address) |
AZURE_PASSWORD |
that user's password |
Variable name | Value |
---|---|
AZURE_CLIENT_ID |
The client ID for the user-assigned managed identity. If defined, used as the default value for ManagedIdentityClientId in DefaultAzureCredentialOptions |
Configuration is attempted in the order in which these environment variables are listed. For example, if values for a client secret and certificate are both present, the client secret is used.
As of version 1.10.0, accessing resources protected by Continuous Access Evaluation (CAE) is possible on a per-request basis. This behavior can be enabled by setting the IsCaeEnabled
property of TokenRequestContext
via its constructor. CAE isn't supported for developer and managed identity credentials.
Token caching is a feature provided by the Azure Identity library. The feature allows apps to:
- Cache tokens in memory (default) or on disk (opt-in).
- Improve resilience and performance.
- Reduce the number of requests made to Microsoft Entra ID to obtain access tokens.
The Azure Identity library offers both in-memory and persistent disk caching. For more information, see the token caching documentation.
An authentication broker is an app that runs on a user's machine and manages the authentication handshakes and token maintenance for connected accounts. Currently, only Windows is supported via Web Account Manager (WAM). To enable support, use the Azure.Identity.Broker package.
See the troubleshooting guide.
Errors arising from authentication can be raised on any service client method that makes a request to the service. This is because the first time the token is requested from the credential is on the first call to the service. Any subsequent calls might need to refresh the token. To distinguish these failures from failures in the service client, Azure Identity classes raise the AuthenticationFailedException
with details on the error source in the exception message and possibly the error message. Depending upon the app, these errors may or may not be recoverable.
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
// Create a secret client using the DefaultAzureCredential
var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), new DefaultAzureCredential());
try
{
KeyVaultSecret secret = await client.GetSecretAsync("secret1");
}
catch (AuthenticationFailedException e)
{
Console.WriteLine($"Authentication Failed. {e.Message}");
}
For more information on handling errors from failed requests to Microsoft Entra ID or managed identity endpoints, see the Microsoft Entra ID documentation on authorization error codes.
See Enable and configure logging.
We guarantee that all credential instance methods are thread-safe and independent of each other (guideline). This ensures that the recommendation of reusing credential instances is always safe, even across threads.
Client options | Accessing the response | Diagnostics | Mocking | Client lifetime
Many of Azure.Core-dependent client libraries support authenticating with TokenCredential
and therefore the Azure Identity library. To learn more, see the library-specific docs.
This library doesn't currently support scenarios relating to the Azure AD B2C service.
Open issues for the Azure.Identity
library can be found here.
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.
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. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.