I want to get secret from Azure key vault.
I found codes below and tried it. But I failed with error.
private String clientId= \'
Before getting secrets from the Azure Key Vault make sure you have access to the key vault. Make sure to login or provide correct Azure credential. you can refer this link for getting secret
Or you execute this powershell command Get-AzureKeyVaultSecret -VaultName 'VaultName' -Name 'sceretName'
It seems that you want to access the azure key vault with application.
Register a web app in Azure AD
You can get the client id (application id) at the overview
Add a secret
Assign access policy in key vault
Save the policy, so that it will take effect.
Code sample
public class KeyVaultTest {
private static AuthenticationResult getAccessToken(String authorization, String resource) throws InterruptedException, ExecutionException, MalformedURLException {
String clientId = "dc17****-****-****-****-ea03****a5e7"; // Client ID
String clientKey = "1YWt******k21"; //Client Secret
AuthenticationResult result = null;
//Starts a service to fetch access token.
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authorization, false, service);
Future<AuthenticationResult> future = null;
//Acquires token based on client ID and client secret.
if (clientKey != null && clientKey != null) {
ClientCredential credentials = new ClientCredential(clientId, clientKey);
future = context.acquireToken(resource, credentials, null);
}
result = future.get();
} finally {
service.shutdown();
}
if (result == null) {
throw new RuntimeException("Authentication results were null.");
}
return result;
}
public static void main(String[] args) {
String vaultBase = "https://jackkv.vault.azure.net/";
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultCredentials(){
@Override
public String doAuthenticate(String authorization, String resource, String scope) {
String token = null;
try {
AuthenticationResult authResult = getAccessToken(authorization, resource);
token = authResult.getAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
});
SecretBundle test = keyVaultClient.getSecret(vaultBase, "test");
System.out.println(test.value());
}
}
Update:
If you face connection issues, please check if you have set the firewall for your key vault.
If you set the firewall, please add your IP to the allowed list: