我正在运行AzureClient java sdk。我创建了这样的keyvault客户端:
ApplicationTokenCredentials applicationTokenCredentials=new
ApplicationTokenCredentials(APPLICATION_ID, "DOMAIN", CLIENT_SECRET,
AzureEnvironment.AZURE);
vc = new KeyVaultClient(applicationTokenCredentials);
我编写此代码以从azure目录获取密钥:
Future<KeyBundle> keyBundleFuture = vc.getKeyAsync(testKeyIdentifier, new ServiceCallback<KeyBundle>() {
public void failure(Throwable throwable) {
}
public void success(KeyBundle keyBundle) {
System.out.print(keyBundle.toString());
}
});
KeyBundle keyBundle = keyBundleFuture.get();
但是我收到了这个错误
Exception in thread "main" java.util.concurrent.ExecutionException: com.microsoft.azure.keyvault.models.KeyVaultErrorException: Status code 401.
另请注意,我已从azure portal授予我的applocation权限以访问keyvault
答案 0 :(得分:2)
根据错误的状态代码401
和密钥保管库的REST API参考Authentication, requests, and responses
,它是由使用Azure Java SDK的错误凭据引起的。要使用Azure SDK访问密钥保管库,必须使用KeyVaultCredentials
进行身份验证,这需要使用方法doAuthenticate
实现。
作为参考,以下是我的示例代码。
ServiceClientCredentials credentials = new KeyVaultCredentials() {
@Override
public String doAuthenticate(String authorization, String resource, String scope) {
AuthenticationResult res = null;
try {
res = GetAccessToken(authorization, resource, clientId, secret);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res.getAccessToken();
}
private AuthenticationResult GetAccessToken(String authorization, String resource, String clientID, String clientKey)
throws InterruptedException, ExecutionException {
AuthenticationContext ctx = null;
ExecutorService service = Executors.newFixedThreadPool(1);
try {
ctx = new AuthenticationContext(authorization, false, service);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Future<AuthenticationResult> resp = ctx.acquireToken(resource, new ClientCredential(
clientID, clientKey), null);
AuthenticationResult res = resp.get();
return res;
}
};
KeyVaultClient client = new KeyVaultClient(credentials);
String keyIdentifier = "https://<your-keyvault>.vault.azure.net/keys/<your-key>/xxxxxxxxxxxxxxxxxxxxxx";
KeyBundle keyBundle = client.getKey(keyIdentifier);
然后,它有效。