Skip to content

Identity and Authentication

Vinay Gera edited this page Feb 24, 2020 · 3 revisions

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();
}

When executing this in a development machine you need to first configure the environment setting the variables AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_CLIENT_SECRET to the appropriate values for your service principal.

Authenticating a service principal with a client secret

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

/**
 *  Authenticate with client secret.
 */
public void createClientSecretCredential() {
    ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
        .clientId("<YOUR_CLIENT_ID>")
        .clientSecret("<YOUR_CLIENT_SECRET>")
        .tenantId("<YOUR_TENANT_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(clientSecretCredential)
        .buildClient();
}

Authenticating with Device code flow

Enable applications for device code flow

In order to authenticate a user through device code flow, you need to go to Azure Active Directory on Azure Portal and find you app registration and enable the following 2 configurations:

device code enable

This will let the application authenticate, but the application still doesn't have permission to log you into Active Directory, or access resources on your behalf. Open API Permissions, and enable Microsoft Graph, and the resources you want to access, e.g., Azure Service Management, Key Vault, etc:

device code permissions

Note that you also need to be the admin of your tenant to grant consent to your application when you login for the first time. Also note after 2018 your Active Directory may require your application to be multi-tenant. Select "Accounts in any organizational directory" under Authentication panel (where you enabled Device Code) to make your application a multi-tenant app.

Authenticating a user account with device code flow

This example demonstrates authenticating the KeyClient from the azure-security-keyvault-keys client library using the DeviceCodeCredential on an IoT device. There's also a compilable sample to create a Key Vault secret client you can copy-paste.

/**
 * Authenticate with device code credential.
 */
public void createDeviceCodeCredential() {
    DeviceCodeCredential deviceCodeCredential = new DeviceCodeCredentialBuilder()
        .challengeConsumer(challenge -> {
            // lets user know of the challenge
            System.out.println(challenge.getMessage());
        })
        .build();

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

Authenticating a user account with username and password

This example demonstrates authenticating the KeyClient from the azure-security-keyvault-keys client library using the UsernamePasswordCredential. The user must not have Multi-factor auth turned on. There's also a compilable sample to create a Key Vault secret client you can copy-paste.

/**
 * Authenticate with username, password.
 */
public void createUserNamePasswordCredential() {
    UsernamePasswordCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder()
        .clientId("<YOUR_CLIENT_ID>")
        .username("<YOUR_USERNAME>")
        .password("<YOUR_PASSWORD>")
        .build();

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

Chaining credentials

The ChainedTokenCredential class provides the ability to link together multiple credential instances to be tried sequentially when authenticating. The following example demonstrates creating a credential which will attempt to authenticate using managed identity, and fall back to certificate authentication if a managed identity is unavailable in the current environment. This example authenticates an EventHubClient from the azure-eventhubs client library using the ChainedTokenCredential. There's also a compilable sample to create a Key Vault secret client you can copy-paste.

/**
 * Authenticate with chained credentials.
 */
public void createChainedCredential() {
    ManagedIdentityCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder()
        .clientId("<YOUR_CLIENT_ID>")
        .build();

    ClientSecretCredential secondServicePrincipal = new ClientSecretCredentialBuilder()
        .clientId("<YOUR_CLIENT_ID>")
        .clientSecret("<YOUR_CLIENT_SECRET>")
        .tenantId("<YOUR_TENANT_ID>")
        .build();

    // when an access token is requested, the chain will try each
    // credential in order, stopping when one provides a token
    ChainedTokenCredential credentialChain = new ChainedTokenCredentialBuilder()
        .addLast(managedIdentityCredential)
        .addLast(secondServicePrincipal)
        .build();

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