Azure工作负载身份联合与托管身份:login.microsoftonline.com返回401错误排查
环境配置
- 已配置指向AKS服务账户的、带有联合身份凭据的用户分配托管标识
- 已启用OIDC颁发者和工作负载身份的AKS集群(版本1.23.8),并配置了服务账户
- 运行中的Pod已注入以下环境变量:
AZURE_AUTHORITY_HOST:https://login.microsoftonline.com/AZURE_CLIENT_ID:<my-client-id>AZURE_FEDERATED_TOKEN_FILE:/var/run/secrets/azure/tokens/azure-identity-tokenAZURE_TENANT_ID:<my-tenant-id>
使用的Maven依赖
<dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.9.0-beta.3</version> <!-- <version>1.7.3</version> tried different versions ... --> </dependency>
Java代码片段
ManagedIdentityCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder() .build(); QueueClient queue = new QueueClientBuilder() .credential(managedIdentityCredential) .endpoint("https://<my-storage-account>.queue.core.windows.net") .queueName("test") .buildClient();
报错信息
java.io.IOException: Server returned HTTP response code: 401 for URL: https://login.microsoftonline.com/<my-tenant-id>/oauth2/v2.0/token
...
[ForkJoinPool.commonPool-worker-3] ERROR com.azure.identity.ManagedIdentityCredential - Azure Identity => ERROR in getToken() call for scopes [https://storage.azure.com/.default]: Managed Identity authentication is not available.
[ForkJoinPool.commonPool-worker-3] ERROR com.azure.core.implementation.AccessTokenCache - Failed to acquire a new access token.
未指定用户分配托管标识的Client ID
默认情况下,ManagedIdentityCredentialBuilder.build()会尝试使用系统分配的托管标识,但你使用的是用户分配托管标识,必须显式指定Client ID。修改代码:ManagedIdentityCredential managedIdentityCredential = new ManagedIdentityCredentialBuilder() .clientId("<my-client-id>") // 填入你的用户分配标识Client ID .build();依赖版本存在兼容性问题
你使用的是预览版1.9.0-beta.3,对AKS工作负载身份的支持可能不完善。建议切换到稳定版,比如1.12.x及以上版本,这些版本对工作负载身份的适配更成熟。环境变量拼接URL出错
报错信息中的URL出现了多余的斜杠(login.microsoftonline.com/\<my-tenant-id>),这是因为AZURE_AUTHORITY_HOST结尾带了斜杠,导致拼接时出现异常。将该环境变量的值改为https://login.microsoftonline.com(去掉末尾的/)。服务账户与托管标识的绑定未生效
重新确认联合身份绑定配置:- 检查用户分配托管标识对应的Azure AD应用程序,是否已正确配置Federated Credentials,受众需为
api://AzureADTokenExchange,实体ID需匹配AKS服务账户格式:system:serviceaccount:<namespace>:<serviceaccount-name> - 确认AKS集群的OIDC颁发者URL已正确配置到Azure AD的Federated Credentials中
- 检查用户分配托管标识对应的Azure AD应用程序,是否已正确配置Federated Credentials,受众需为
存储账户RBAC权限缺失
确保用户分配托管标识已被授予存储队列的相关权限(如Storage Queue Data Contributor),且权限已生效。可通过Azure CLI验证:az role assignment list --assignee <my-client-id> --scope "/subscriptions/<subscription-id>/resourceGroups/<rg-name>/providers/Microsoft.Storage/storageAccounts/<storage-account-name>"
内容的提问来源于stack exchange,提问作者sl3dg3

