How to ignore errors from WorkloadIdentityCredentialBuilder?

71 views Asked by At

We are using azure-identity java library and the below code to get TokenCredential which is in turn used to access azure resources.

public TokenCredential buildCredential() {
    return new ChainedTokenCredentialBuilder()
        .addFirst(new WorkloadIdentityCredentialBuilder().build())
        .addLast(new AzureCliCredentialBuilder().build())
        .build();
}

When we are trying to debug locally we are getting below exception and it stops processing.

IllegalArgumentException: Must provide non-null values for Client ID, Tenant ID, Service Token File Path properties in WorkloadIdentityCredentialBuilder

We have found below solution. Is it possible to implement it using the earlier code without depending on active profiles? Our expectation is that it should continue processing without throwing any exception and use AzureCliCredentialBuilder.

public TokenCredential buildCredential() {
    if (activeProfiles != null && activeProfiles.contains("local")) {
        return new AzureCliCredentialBuilder().build();
    }

    return new WorkloadIdentityCredentialBuilder().build();
}
2

There are 2 answers

1
Venkatesan On

The IllegalArgumentException error occurred due to missing required parameters for WorkloadIdentityCredentialBuilder.

If you want to ignore errors from WorkloadIdentityCredentialBuilder, you can catch the CredentialUnavailableException that it throws and continue with the next credential in the chain, which is AzureCliCredentialBuilder in your case.

Here's an updated version of your buildCredential method that implements this approach:

public TokenCredential buildCredential() {
    try {
        return new ChainedTokenCredentialBuilder()
            .addFirst(new WorkloadIdentityCredentialBuilder().build())
            .addLast(new AzureCliCredentialBuilder().build())
            .build();
    } catch (CredentialUnavailableException e) {
        // WorkloadIdentityCredentialBuilder is not available, ignore and try AzureCliCredentialBuilder
        return new AzureCliCredentialBuilder().build();
    }
}

This will try to get a token from WorkloadIdentityCredentialBuilder first, and if it's not available, it will catch the CredentialUnavailableException and try to get a token from AzureCliCredentialBuilder

Reference:

Troubleshoot Azure-hosted application authentication - Azure SDK for Java | Microsoft Learn

0
Venky On
public TokenCredential buildCredential() {
    if (activeProfiles != null && activeProfiles.contains("local")) {
        return new AzureCliCredentialBuilder().build();
    }

    return new WorkloadIdentityCredentialBuilder().build();
}