Unable to read secret from Azure Key Vault Using Username & Password or Enviroment Variables With Java

David Aw 0 Reputation points
2023-11-01T08:09:46.0233333+00:00

Dear Seniors,

How to retrieve secret key from Azure Key Vault using username and password and client id?

where do I create/retrieve this client id?

I have no issue running the code below using Azure CLI just by running az login

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

But when I set the code to environment variable like this [enter image description here

](https://i.stack.imgur.com/U1HUq.png)

I will encounter this

com.azure.identity.CredentialUnavailableException: EnvironmentCredential authentication unavailable. Environment variables
 are not fully configured.To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/az
sdk/java/identity/environmentcredential/troubleshoot

I know where to find azure_tenant_id but where do I create the AZURE_CLIENT_ID and AZURE_CLIENT_SECRET?

I also try this code

UsernamePasswordCredential usernamePasswordCredential = new UsernamePasswordCredentialBuilder()
            .clientId("xxxxxxxxxxxxxxxx1e60e93e1ccf")
            .username("xxxxxxxxxxxx")
            .password("xxxxxxxxxxx")
            .build();

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

And I got this error

com.azure.core.exception.ClientAuthenticationException: Failed to acquire token with username and password. To mitigate th
is issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/java/identity/usernamepasswordcreden
tial/troubleshoot
        at com.azure.identity.implementation.IdentityClient.lambda$authenticateWithUsernamePassword$30(IdentityClient.java
:582)
        at reactor.core.publisher.Mono.lambda$onErrorMap$31(Mono.java:3811)
        at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:94)
        at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:192)
        at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:259)
        at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:94)
        at java.base/java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:930)
        at java.base/java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:907)
        at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506)
        at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1705)
        at java.base/java.lang.Thread.run(Thread.java:829)
        Suppressed: com.azure.core.exception.ClientAuthenticationException: Failed to acquire token with username and pass
word. To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/java/identity/us
ernamepasswordcredential/troubleshoot
                ... 11 more
        Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS7000218: The request body must contain the followi
ng parameter: 'client_assertion' or 'client_secret'. Trace ID: 4957ee5b-ea2d-4e84-8492-10e2efdb4900 Correlation ID: fe1995
94-35eb-4c3e-9b2e-85e38f108f68 Timestamp: 2023-11-01 07:56:17Z
                at com.microsoft.aad.msal4j.MsalServiceExceptionFactory.fromHttpResponse(MsalServiceExceptionFactory.java:
45)
                at com.microsoft.aad.msal4j.TokenRequestExecutor.createAuthenticationResultFromOauthHttpResponse(TokenRequ
estExecutor.java:161)
                at com.microsoft.aad.msal4j.TokenRequestExecutor.executeTokenRequest(TokenRequestExecutor.java:40)
                at com.microsoft.aad.msal4j.AbstractClientApplicationBase.acquireTokenCommon(AbstractClientApplicationBase
.java:256)
                at com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGr
antSupplier.java:63)
                at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:69)
                at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:18)
                at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
                ... 1 more
        Suppressed: com.azure.core.exception.ClientAuthenticationException: Failed to acquire token with username and pass
word. To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/java/identity/us
ernamepasswordcredential/troubleshoot
                ... 11 more
        Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS7000218: The request body must contain the followi
ng parameter: 'client_assertion' or 'client_secret'. Trace ID: a2eba876-aa5c-4b10-8316-9bb8fdc24d00 Correlation ID: 1b8562
10-db80-4b30-85eb-4de206992171 Timestamp: 2023-11-01 07:56:19Z
                at com.microsoft.aad.msal4j.MsalServiceExceptionFactory.fromHttpResponse(MsalServiceExceptionFactory.java:
45)
                at com.microsoft.aad.msal4j.TokenRequestExecutor.createAuthenticationResultFromOauthHttpResponse(TokenRequ
estExecutor.java:161)
                at com.microsoft.aad.msal4j.TokenRequestExecutor.executeTokenRequest(TokenRequestExecutor.java:40)
                at com.microsoft.aad.msal4j.AbstractClientApplicationBase.acquireTokenCommon(AbstractClientApplicationBase
.java:256)
                at com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGr
antSupplier.java:63)
                at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:69)
                at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:18)
                at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
                ... 1 more
        Suppressed: com.azure.core.exception.ClientAuthenticationException: Failed to acquire token with username and pass
word. To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/java/identity/us
ernamepasswordcredential/troubleshoot
                ... 11 more
        Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS7000218: The request body must contain the followi
ng parameter: 'client_assertion' or 'client_secret'. Trace ID: 60dc7021-d436-4a5f-9499-4729bb732500 Correlation ID: 8fca47
e8-07c8-44d4-a2eb-f4fb6670d281 Timestamp: 2023-11-01 07:56:22Z
                at com.microsoft.aad.msal4j.MsalServiceExceptionFactory.fromHttpResponse(MsalServiceExceptionFactory.java:
45)
                at com.microsoft.aad.msal4j.TokenRequestExecutor.createAuthenticationResultFromOauthHttpResponse(TokenRequ
estExecutor.java:161)
                at com.microsoft.aad.msal4j.TokenRequestExecutor.executeTokenRequest(TokenRequestExecutor.java:40)
                at com.microsoft.aad.msal4j.AbstractClientApplicationBase.acquireTokenCommon(AbstractClientApplicationBase
.java:256)
                at com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGr
antSupplier.java:63)
                at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:69)
                at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:18)
                at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
                ... 1 more
        Suppressed: java.lang.Exception: #block terminated with an error
                at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:100)
                at reactor.core.publisher.Mono.block(Mono.java:1742)
                at com.azure.security.keyvault.secrets.SecretClient.getSecretWithResponse(SecretClient.java:171)
                at com.azure.security.keyvault.secrets.SecretClient.getSecret(SecretClient.java:150)
                at com.blobs.quickstart.appupload.main(appupload.java:97)
Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS7000218: The request body must contain the following param
eter: 'client_assertion' or 'client_secret'. Trace ID: 2d91e058-2470-4f25-ba8e-3eac892d8300 Correlation ID: b5cf0277-fdea-
438b-8388-f6a8184d2492 Timestamp: 2023-11-01 07:56:26Z
        at com.microsoft.aad.msal4j.MsalServiceExceptionFactory.fromHttpResponse(MsalServiceExceptionFactory.java:45)
        at com.microsoft.aad.msal4j.TokenRequestExecutor.createAuthenticationResultFromOauthHttpResponse(TokenRequestExecu
tor.java:161)
        at com.microsoft.aad.msal4j.TokenRequestExecutor.executeTokenRequest(TokenRequestExecutor.java:40)
        at com.microsoft.aad.msal4j.AbstractClientApplicationBase.acquireTokenCommon(AbstractClientApplicationBase.java:25
6)
        at com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGrantSuppl
ier.java:63)
        at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:69)
        at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:18)
        at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
        ... 1 more


Azure Key Vault
Azure Key Vault
An Azure service that is used to manage and protect cryptographic keys and other secrets used by cloud apps and services.
1,256 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Shweta Mathur 29,741 Reputation points Microsoft Employee
    2023-11-06T11:15:51.25+00:00

    Hi @David Aw ,

    Thanks for reaching out.

    It seems you are trying to fetch Key Vault's secret and facing an issue while fetching the credentials.

    I can see you have used UsernamePasswordCredential and DefaultAzureCredential classes to authenticate the requests.

    If you are working in Visual Studio, then vsual studio sometimes don't pick the credentials which causes this error.

    In Visual Studio, go to Tools > Options. Expand "Azure Service Authentication" > "Account Selection." If you see a "Reenter your credentials" link, click it and sign in again. If not, try a regular sign-out + sign-in via your Visual Studio profile in the top right.

    Alternatively, you can authenticate yourself by creating a service principal and setting client secret for that application and then connect with key vault to retrieve the value.

    Reference to create service principal-

    https://learn.microsoft.com/en-us/entra/identity-platform/howto-create-service-principal-portal

    You can get the client id and client secret of the application when you registered your application.
    User's image

    Hope this will help.

    Thanks,

    Shweta


    Please remember to "Accept Answer" if answer helped you.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.