Skip navigation links

Azure SDK for Java Reference Documentation

Current version is 1.4.0-beta.1, click here for the index

Azure Identity client library for Java

See: Description

Packages 
Package Description
com.azure.identity
Package containing various types of credentials and classes for retrieving access tokens from various configurations.
Current version is 1.4.0-beta.1, click here for the index

Azure Identity client library for Java

The Azure Identity library provides Azure Active Directory (AAD) token authentication through a set of convenient TokenCredential implementations. It enables Azure SDK clients to authenticate with AAD, while also allowing other Java apps to authenticate with AAD work and school accounts, Microsoft personal accounts (MSA), and other Identity providers through the AAD B2C service.

Source code | API reference documentation | Azure Active Directory documentation

Getting started

Include the package

Include the BOM file

Please include the azure-sdk-bom to your project to take dependency on GA version of the library. In the following snippet, replace the {bomversionto_target} placeholder with the version number. To learn more about the BOM, see the AZURE SDK BOM README.

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

and then include the direct dependency in the dependencies section without the version tag.

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
  </dependency>
</dependencies>

Include direct dependency

If you want to take dependency on a particular version of the library that is not present in the BOM, add the direct dependency to your project as follows.

Maven dependency for Azure Secret Client library. Add it to your project's pom file.

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.3.6</version>
</dependency>

Prerequisites

Authenticate the client

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:

Click on each item above to learn about how to configure them for Azure Identity authentication.

Key concepts

Credentials

A credential is a class which contains or can obtain the data needed for a service client to authenticate requests. Service clients across Azure SDK accept credentials when they are constructed, and service clients use those credentials to authenticate requests to the service.

The Azure Identity library focuses on OAuth authentication with Azure Active directory, and it offers a variety of credential classes capable of acquiring an AAD 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 by to construct service clients capable of authenticating with a TokenCredential.

See Credential Classes for a complete list of available credential classes.

DefaultAzureCredential

The DefaultAzureCredential is appropriate for most scenarios where the application is intended to ultimately be run in the Azure Cloud. 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 will attempt to authenticate via the following mechanisms in order.

DefaultAzureCredential authentication flow

Examples

You can find more examples of using various credentials in Azure Identity Examples Wiki page.

Authenticating with DefaultAzureCredential

This example demonstrates authenticating the SecretClient from the azure-security-keyvault-secrets client library using the DefaultAzureCredential. There's also a compilable sample to create a Key Vault secret client you can copy-paste.

/**
 * The default credential first checks environment variables for configuration.
 * If environment configuration is incomplete, it will try managed identity.
 */
public void createDefaultAzureCredential() {
    DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();

    // Azure SDK client builders accept the credential as a parameter
    SecretClient client = new SecretClientBuilder()
        .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net")
        .credential(defaultCredential)
        .buildClient();
}

See more how to configure the DefaultAzureCredential on your workstation or Azure in Configure DefaultAzureCredential.

Authenticating a user assigned managed identity with DefaultAzureCredential

This example demonstrates authenticating the SecretClient from the azure-security-keyvault-secrets client library using the DefaultAzureCredential, deployed to an Azure resource with a user assigned managed identity configured.

See more about how to configure a user assigned managed identity for an Azure resource in Enable managed identity for Azure resources.

/**
 * The default credential will use the user assigned managed identity with the specified client ID.
 */
public void createDefaultAzureCredentialForUserAssignedManagedIdentity() {
    DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
        .managedIdentityClientId("<MANAGED_IDENTITY_CLIENT_ID>")
        .build();

    // Azure SDK client builders accept the credential as a parameter
    SecretClient client = new SecretClientBuilder()
        .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net")
        .credential(defaultCredential)
        .buildClient();
}

In addition to configuring the managedIdentityClientId via code, it can also be set using the AZURE_CLIENT_ID environment variable. These two approaches are equivalent when using the DefaultAzureCredential.

Authenticating a user in Azure Toolkit for IntelliJ with DefaultAzureCredential

This example demonstrates authenticating the SecretClient from the azure-security-keyvault-secrets client library using the DefaultAzureCredential, on a workstation with IntelliJ IDEA installed, and the user has signed in with an Azure account to the Azure Toolkit for IntelliJ.

See more about how to configure your IntelliJ IDEA in Sign in Azure Toolkit for IntelliJ for IntelliJCredential.

/**
 * The default credential will use the KeePass database path to find the user account in IntelliJ on Windows.
 */
public void createDefaultAzureCredentialForIntelliJ() {
    DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
        // KeePass configuration required only for Windows. No configuration needed for Linux / Mac
        .intelliJKeePassDatabasePath("C:\\Users\\user\\AppData\\Roaming\\JetBrains\\IdeaIC2020.1\\c.kdbx")
        .build();

    // Azure SDK client builders accept the credential as a parameter
    SecretClient client = new SecretClientBuilder()
        .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net")
        .credential(defaultCredential)
        .buildClient();
}

Managed Identity Support

The Managed identity authentication is supported via either the DefaultAzureCredential or the ManagedIdentityCredential directly for the following Azure Services: * Azure Virtual Machines * Azure App Service * Azure Kubernetes Service * Azure Cloud Shell * Azure Arc * Azure Service Fabric

Examples

Authenticating in Azure with Managed Identity

This examples demonstrates authenticating the SecretClient from the azure-security-keyvault-secrets client library using the ManagedIdentityCredential in a virtual machine, app service, function app, cloud shell, or AKS environment on Azure, with system assigned, or user assigned managed identity enabled.

see more about how to configure your Azure resource for managed identity in Enable managed identity for Azure resources

/**
 * Authenticate with a User Assigned Managed identity.
 */
public void createManagedIdentityCredential() {
    ManagedIdentityCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder()
        .clientId("<USER ASSIGNED MANAGED IDENTITY CLIENT ID>") // only required for user assigned
        .build();

    // Azure SDK client builders accept the credential as a parameter
    SecretClient client = new SecretClientBuilder()
        .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net")
        .credential(managedIdentityCredential)
        .buildClient();
}
/**
 * Authenticate with a System Assigned Managed identity.
 */
public void createManagedIdentityCredential() {
    ManagedIdentityCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder()
        .build();

    // Azure SDK client builders accept the credential as a parameter
    SecretClient client = new SecretClientBuilder()
        .vaultUrl("https://{YOUR_VAULT_NAME}.vault.azure.net")
        .credential(managedIdentityCredential)
        .buildClient();
}

Credential classes

Authenticating Azure Hosted Applications

credential class usage configuration example
DefaultAzureCredential provides a simplified authentication experience to quickly start developing applications run in the Azure cloud configuration example
ChainedTokenCredential allows users to define custom authentication flows composing multiple credentials example
EnvironmentCredential authenticates a service principal or user via credential information specified in environment variables
ManagedIdentityCredential authenticates the managed identity of an azure resource configuration example

Authenticating Service Principals

credential class usage configuration example reference
ClientSecretCredential authenticates a service principal using a secret configuration example Service principal authentication
ClientCertificateCredential authenticates a service principal using a certificate configuration example Service principal authentication

Authenticating Users

credential class usage configuration example reference
DeviceCodeCredential interactively authenticates a user on devices with limited UI configuration example Device code authentication
InteractiveBrowserCredential interactively authenticates a user with the default system browser configuration example OAuth2 authentication code
UsernamePasswordCredential authenticates a user with a username and password without multi-factored auth example Username + password authentication
AuthorizationCodeCredential authenticate a user with a previously obtained authorization code as part of an Oauth 2 flow configuration OAuth2 authentication code

Authenticating via Development Tools

credential class usage configuration example reference
AzureCliCredential authenticate in a development environment with the enabled user or service principal in Azure CLI configuration example Azure CLI authentication
IntelliJCredential authenticate in a development environment with the account in Azure Toolkit for IntelliJ configuration example IntelliJ authentication
VisualStudioCodeCredential authenticate in a development environment with the account in Visual Studio Azure Account extension configuration example VS Code Azure extension

Note: All credential implementations in the Azure Identity library are threadsafe, and a single credential instance can be used to create multiple service clients.

Credentials can be chained together to be tried in turn until one succeeds using the ChainedTokenCredential; see chaining credentials for details.

Environment Variables

DefaultAzureCredential and EnvironmentCredential can be configured with environment variables. Each type of authentication requires values for specific variables:

Service principal with secret

variable name value
AZURE_CLIENT_ID id of an Azure Active Directory application
AZURE_TENANT_ID id of the application's Azure Active Directory tenant
AZURE_CLIENT_SECRET one of the application's client secrets

Service principal with certificate

variable name value
AZURE_CLIENT_ID id of an Azure Active Directory application
AZURE_TENANT_ID id of the application's Azure Active Directory tenant
AZURE_CLIENT_CERTIFICATE_PATH path to a PEM-encoded certificate file including private key (without password protection)

Username and password

variable name value
AZURE_CLIENT_ID id of an Azure Active Directory application
AZURE_USERNAME a username (usually an email address)
AZURE_PASSWORD that user's password

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.

Troubleshooting

Credentials raise exceptions either when they fail to authenticate or cannot execute authentication. When credentials fail to authenticate, theClientAuthenticationException is raised and it has a message attribute which describes why authentication failed. When this exception is raised by ChainedTokenCredential, the chained execution of underlying list of credentials is stopped.

When credentials cannot execute authentication due to one of the underlying resources required by the credential being unavailable on the machine, theCredentialUnavailableException is raised and it has a message attribute which describes why the credential is unavailable for authentication execution . When this exception is raised by ChainedTokenCredential, the message collects error messages from each credential in the chain.

Enable client logging

Azure SDK for Java offers a consistent logging story to help aid in troubleshooting application errors and expedite their resolution. The logs produced will capture the flow of an application before reaching the terminal state to help locate the root issue. View the logging wiki for guidance about enabling logging.

Next steps

The java client libraries listed here support authenticating with TokenCredential and the Azure Identity library. You can learn more about their use, and find additional documentation on use of these client libraries along samples with can be found in the links mentioned here.

The [microsoft-graph-sdk][https://github.com/microsoftgraph/msgraph-sdk-java] also supports authenticating with TokenCredential and the Azure Identity library.

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.

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.

Impressions

Skip navigation links
Visit the Azure for Java Developerssite for more Java documentation, including quick starts, tutorials, and code samples.

Copyright © 2021 Microsoft Corporation. All rights reserved.