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 which can be used to construct Azure SDK clients which 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 is typical for a developer to use their own account for authenticating calls to Azure services. There are several developer tools which 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. Applications using the DefaultAzureCredential
or the VisualStudioCredential
can then use this account to authenticate calls in their application 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. Applications using the DefaultAzureCredential
or the VisualStudioCodeCredential
can then use this account to authenticate calls in their application 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, consider authenticating via the Azure CLI.
Developers coding outside of an IDE can also use the Azure CLI to authenticate. Applications using the DefaultAzureCredential
or the AzureCliCredential
can then use this account to authenticate calls in their application when running locally.
To authenticate with the Azure CLI, users can run the command az login
. For users running on a system with a default web browser, the Azure CLI will launch the browser to authenticate the user.
For systems without a default web browser, the az login
command will use 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. Applications using the DefaultAzureCredential
or the AzureDeveloperCliCredential
can then use this account to authenticate calls in their application when running locally.
To authenticate with the Azure Developer CLI, users can run the command azd auth login
. For users running on a system with a default web browser, the Azure Developer CLI will launch the browser to authenticate the user.
For systems without a default web browser, the azd auth login --use-device-code
command will use the device code authentication flow.
Developers coding outside of an IDE can also use Azure PowerShell to authenticate. Applications using the DefaultAzureCredential
or the AzurePowerShellCredential
can then use this account to authenticate calls in their application when running locally.
To authenticate with Azure PowerShell, users can 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 will launch the browser to authenticate the user.
For systems without a default web browser, the Connect-AzAccount
command will use 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 which 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, and it offers a variety of credential classes capable of acquiring a Microsoft Entra token to authenticate service requests. All of the credential classes in this library are implementations 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.
The DefaultAzureCredential
is appropriate for most scenarios where the application is intended to ultimately be run in Azure. This is because the DefaultAzureCredential
combines credentials commonly used to authenticate when deployed, with credentials used to authenticate in a development environment.
Note:
DefaultAzureCredential
is intended to simplify getting started with the SDK by handling common scenarios with reasonable default behaviors. Developers who want more control or whose scenario isn't served by the default settings should use other credential types.
The DefaultAzureCredential
attempts to authenticate via the following mechanisms, in this order, stopping when one succeeds:
- Environment - The
DefaultAzureCredential
will read account information specified via environment variables and use it to authenticate. - Workload Identity - If the application is deployed to an Azure host with Workload Identity enabled, the
DefaultAzureCredential
will authenticate with that account. - Managed Identity - If the application is deployed to an Azure host with Managed Identity enabled, the
DefaultAzureCredential
will authenticate with that account. - Visual Studio - If the developer has authenticated via Visual Studio, the
DefaultAzureCredential
will authenticate with that account. - Visual Studio Code - Currently excluded by default as SDK authentication via Visual Studio Code is broken due to issue #27263. The
VisualStudioCodeCredential
will be re-enabled in theDefaultAzureCredential
flow once a fix is in place. Issue #30525 tracks this. In the meantime Visual Studio Code users can authenticate their development environment using the Azure CLI. - Azure CLI - If the developer has authenticated an account via the Azure CLI
az login
command, theDefaultAzureCredential
will authenticate with that account. - Azure PowerShell - If the developer has authenticated an account via the Azure PowerShell
Connect-AzAccount
command, theDefaultAzureCredential
will authenticate with that account. - Azure Developer CLI - If the developer has authenticated via the Azure Developer CLI
azd auth login
command, theDefaultAzureCredential
will authenticate with that account. - Interactive browser - If enabled, the
DefaultAzureCredential
will interactively authenticate the developer via the current system's default browser. By default, this credential type is disabled.
As of version 1.10.1, DefaultAzureCredential
will attempt 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 will 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 credentials would similarly stop the authentication flow if token retrieval failed.
This behavior allows for trying all of the developer credentials on your machine while having predictable deployed behavior.
This example demonstrates authenticating the SecretClient
from the Azure.Security.KeyVault.Secrets client library using the DefaultAzureCredential
.
// Create a secret client using the DefaultAzureCredential
var client = new SecretClient(new Uri("https://myvault.vault.azure.net/"), new DefaultAzureCredential());
Interactive authentication is disabled in the DefaultAzureCredential
by default. This example demonstrates two ways of enabling the interactive authentication portion of the DefaultAzureCredential
. When enabled the DefaultAzureCredential
will fall back to interactively authenticating the developer via the system's default browser if when no other credentials are available. This example then authenticates an EventHubProducerClient
from the Azure.Messaging.EventHubs client library using the DefaultAzureCredential
with interactive authentication enabled.
// the includeInteractiveCredentials constructor parameter can be used to enable interactive authentication
var credential = new DefaultAzureCredential(includeInteractiveCredentials: true);
var eventHubClient = new EventHubProducerClient("myeventhub.eventhubs.windows.net", "myhubpath", credential);
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 the DefaultAzureCredential
is generally the quickest way to get started developing applications for Azure, more advanced users may want to customize the credentials considered when authenticating. The ChainedTokenCredential
enables users to combine multiple credential instances to define a customized chain of credentials. This example demonstrates creating a ChainedTokenCredential
which will attempt to authenticate using managed identity, and fall back to authenticating via the Azure CLI if managed identity is unavailable in the current environment. The credential is then used to authenticate an EventHubProducerClient
from the Azure.Messaging.EventHubs client library.
// Authenticate using managed identity if it is available; otherwise use the Azure CLI to authenticate.
var credential = new ChainedTokenCredential(new ManagedIdentityCredential(), new AzureCliCredential());
var eventHubProducerClient = new EventHubProducerClient("myeventhub.eventhubs.windows.net", "myhubpath", credential);
Managed identity authentication is supported via either the DefaultAzureCredential
or the ManagedIdentityCredential
directly 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 the SecretClient
from the Azure.Security.KeyVault.Secrets client library using the 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);
Credentials default to authenticating to the Microsoft Entra endpoint for the Azure public cloud. To access resources in other clouds, such as Azure Government or a private cloud, configure credentials with the AuthorityHost
argument. AzureAuthorityHosts defines authorities for well-known clouds:
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzureGovernment });
Not all credentials require this configuration. Credentials which authenticate through a development tool, such as AzureCliCredential
, use that tool's configuration.
Credential | Usage |
---|---|
DefaultAzureCredential |
Provides a simplified authentication experience to quickly start developing applications run in Azure. |
ChainedTokenCredential |
Allows users to define custom authentication flows composing multiple credentials. |
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 above order. For example, if values for a client secret and certificate are both present, the client secret will be 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 details, see the token caching documentation.
An authentication broker is an application that runs on a user’s machine and manages the authentication handshakes and token maintenance for connected accounts. Currently, only the Windows Web Account Manager (WAM) is supported. To enable support, use the Azure.Identity.Broker
package. For details on authenticating using WAM, see the broker package documentation.
See the troubleshooting guide for details on how to diagnose various failure scenarios.
Errors arising from authentication can be raised on any service client method which 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, and any subsequent calls might need to refresh the token. In order to distinguish these failures from failures in the service client Azure Identity classes raise the AuthenticationFailedException
with details to the source of the error in the exception message as well as possibly the error message. Depending on the application 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 dealing with errors arising from failed requests to Microsoft Entra ID or managed identity endpoints, see the Microsoft Entra ID documentation on authorization error codes.
The Azure Identity library provides the same logging capabilities as the rest of the Azure SDK.
The simplest way to see the logs to help debug authentication issues is to enable the console logging.
// Setup a listener to monitor logged events.
using AzureEventSourceListener listener = AzureEventSourceListener.CreateConsoleLogger();
All credentials can be configured with diagnostic options, in the same way as other clients in the SDK.
CAUTION: Requests and responses in the Azure Identity library contain sensitive information. Precaution must be taken to protect logs, when customizing the output, to avoid compromising account security.
DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions
{
Diagnostics =
{
LoggedHeaderNames = { "x-ms-request-id" },
LoggedQueryParameters = { "api-version" },
IsLoggingContentEnabled = true
}
};
When troubleshooting authentication issues, you may also want to enable logging of sensitive information. To enable this type of logging, set the IsLoggingContentEnabled
property to true
. To only log details about the account that was used to attempt authentication and authorization, set IsAccountIdentifierLoggingEnabled
to true
.
DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions
{
Diagnostics =
{
LoggedHeaderNames = { "x-ms-request-id" },
LoggedQueryParameters = { "api-version" },
IsAccountIdentifierLoggingEnabled = true
}
};
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 the client libraries listed here support authenticating with TokenCredential
and the Azure Identity library.
There you will also find links where you can learn more about their use, including additional documentation and samples.
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 will 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.