Reputation: 33
I have Key Vault on Azure and I added Access policies for App registrations with Secret permissions (Get, List, Set, Delete, Recover, Backup, Restore) I wrote Java code:
String keyVaultUri = "https://myKeyVault.azure.net";
ClientSecretCredential paramClientSecretCredential = new ClientSecretCredentialBuilder()
.clientId("MyApplicationId")
.clientSecret("MyApplicationSecretKey")
.tenantId("MyTenantId")
.build();
SecretClient secretClient = new SecretClientBuilder()
.vaultUrl(keyVaultUri)
.credential(paramClientSecretCredential)
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.buildClient();
KeyVaultSecret storedSecret = secretClient.getSecret("mySecret");
System.out.println("Secret value: "+storedSecret.getValue());
I'm using these Maven dependencies:
After I started my code I got this error message Status code 401, "{"error":{"code":"Unauthorized","message":"AKV10000: Request is missing a Bearer or PoP token."}}"
Do you have any suggestions on how to fix this?
Upvotes: 0
Views: 6900
Reputation: 3649
I made some changes with your code and I got the secrete of my key vault at output.
Code:
import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;
import com.azure.security.keyvault.secrets.models.KeyVaultSecret;
public class KeyVaultKam {
public static void main(String[] args) {
String keyVaultUri = "https://<keyvault-name>.vault.azure.net/";
String secretName = "<secrete-name>";
ClientSecretCredential credential = new ClientSecretCredentialBuilder()
.clientId("<client-ID>")
.clientSecret("<client-secrete>")
.tenantId("<tenant-ID>")
.build();
SecretClient secretClient = new SecretClientBuilder()
.vaultUrl(keyVaultUri)
.credential(credential)
.buildClient();
try {
KeyVaultSecret secret = secretClient.getSecret(secretName);
System.out.println("Secret value: " + secret.getValue());
} catch (Exception e) {
System.out.println("Error retrieving secret: " + e.getMessage());
}
}
}
pom.xml:
I added below dependencies to the pom.xml file,
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-security-keyvault-secrets</artifactId>
<version>4.6.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-core</artifactId>
<version>1.39.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
I created access policy for the client application as below,
Output:
It runs successfully and got the output of my secrete as below,
Upvotes: 0