getKey 上的 Azure KeyVaultErrorException

Azure KeyVaultErrorException on getKey

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

根据您的错误状态代码 401 和 REST API 参考 Authentication, requests, and responses of Key Vault, it was caused by using incorrect credentials with Azure Java SDK. To access Key Vault using Azure SDK must be authenticated with KeyVaultCredentials which need to be implemented the method 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);

然后,它起作用了。