在使用应用程序访问Key Vault获取密钥信息时,现后遇见了多种认证错误。使用的代码为:
String keyVaultUrl = "https://test-xxx.vault.azure.cn/"
String keyName = "keyvault-xxx";
KeyClient keyClient = new KeyClientBuilder()
.vaultUrl(keyVaultUrl)
.credential(new DefaultAzureCredentialBuilder()
.tenantId("3c858e6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
.managedIdentityClientId("3df5246c-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
.build())
.buildClient();
KeyVaultKey key = keyClient.getKey(keyName);
遇见的错误一:
Error Details: AADSTS90002: Tenant '3c858e6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx' not found. This may happen if there are no active subscriptions for the tenant. Check to make sure you have the correct tenant ID. Check with your subscription administrator
错误分析:
根据Key Vaule的URL判断,服务位于中国区的Azure中,由于中国区的Azure和Globa Azure是两个独立的云环境,所以在使用SDK登录中国区Azure环境时,需要指定Authority Host。所以需要在代码中加入 " .authorityHost(AzureAuthorityHosts.AZURE_CHINA) “。
修改后的代码为:
String keyVaultUrl = "https://test-xxx.vault.azure.cn/"
String keyName = "keyvault-xxx";
KeyClient keyClient = new KeyClientBuilder()
.vaultUrl(keyVaultUrl)
.credential(new DefaultAzureCredentialBuilder()
.tenantId("3c858e6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
.authorityHost(AzureAuthorityHosts.AZURE_CHINA)
.managedIdentityClientId("3df5246c-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
.build())
.buildClient();
KeyVaultKey key = keyClient.getKey(keyName);
遇见的错误二:
IntelliJ Authentication not available. Please log in with Azure Tools for IntelliJ plugin in the IDE
Status code 403, "{"error":{"code":"Forbidden","message":"The policy requires the caller 'appid=60015a25-xxxx-xxxx-xxxx-xxxxxxxxxxxx;oid=dc107e73-xxxx-xxxx-xxxx-xxxxxxxxxxxx;iss=https://sts.chinacloudapi.cn/3c858e6a-xxxx-xxxx-xxxx-xxxxxxxxxxxx/' to use on-behalf-of (OBO) flow. For more information on OBO, please see https://go.microsoft.com/fwlink/?linkid=2152310","innererror":{"code":"ForbiddenByPolicy"}}}"
错误分析:
因为访问Azure Key Vault需要添加访问策略,需要为当前使用的 Client ID (3df5246c-xxxx-xxxx-xxxx-xxxxxxxxxxxx)配置 访问策略[Access Policy]
遇见的错误三:
认证主题不是自定义的AAD注册应用,而是服务主体(Service Principal) , 所以需要使用 ClientSecretCredential 对象进行认证,而不是默认的 DefaultAzureCredentialBuilder 。
使用ClientSecretCredential 认证的参考代码为:
/**
* Authenticate with client secret.
*/
ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId("<your client ID>")
.clientSecret("<your client secret>")
.tenantId("<your tenant ID>")
.authorityHost(AzureAuthorityHosts.AZURE_CHINA)
.build();
// Azure SDK client builders accept the credential as a parameter.
SecretClient client = new SecretClientBuilder()
.vaultUrl("https://<your Key Vault name>.vault.azure.net")
.credential(clientSecretCredential)
.buildClient();
参考资料:
Client secret credential:https://docs.microsoft.com/en-us/azure/developer/java/sdk/identity-service-principal-auth#client-secret-credential
对 Azure 托管的 Java 应用程序进行身份验证: https://docs.microsoft.com/zh-cn/azure/developer/java/sdk/identity-azure-hosted-auth
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!