gpt4 book ai didi

java - getKey 上的 Azure KeyVaultErrorException

转载 作者:行者123 更新时间:2023-11-30 02:28:32 25 4
gpt4 key购买 nike

我正在运行 AzureClient java sdk。我像这样创建 keyvault 客户端:

ApplicationTokenCredentials applicationTokenCredentials=new 
ApplicationTokenCredentials(APPLICATION_ID, "DOMAIN", CLIENT_SECRET,
AzureEnvironment.AZURE);
vc = new KeyVaultClient(applicationTokenCredentials);

我编写此代码是为了从 azure 目录获取 key :

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 门户向我的应用程序授予访问 keyvault 的权限

最佳答案

根据您的错误的状态代码 401 和 REST API 引用 Authentication, requests, and responses Key Vault 的问题是由于 Azure Java SDK 使用了不正确的凭据造成的。要使用 Azure SDK 访问 Key Vault,必须使用 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);

然后,它就可以工作了。

关于java - getKey 上的 Azure KeyVaultErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44907686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com