Azure ML Workspace中运行OpenAI AAD集成教程时认证令牌获取失败求助
- 试用OpenAI AAD集成Notebook教程,未在本地运行,而是在Azure机器学习工作区(AML Workspace)中运行Notebook,未执行
az login - AML Workspace与Azure OpenAI资源分属不同资源组
- 已为名为
aoai-example-workspace的AML Workspace分配Cognitive Services User角色 - 运行代码时触发
ClientAuthenticationError,DefaultAzureCredential无法从任何凭证源获取token
运行代码
prompt = "Once upon a time" response = get_completion( prompt=prompt, temperature=0.7, max_tokens=300, top_p=0.5, stop=None ) # printing the response print(response)
错误信息
EnvironmentCredential.get_token failed: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
ManagedIdentityCredential.get_token failed: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.
Require a package "gir1.2-secret-1" which could be installed by:
sudo apt install gir1.2-secret-1Traceback (most recent call last):
File "/home/trusted-service-user/cluster-env/env/lib/python3.8/site-packages/msal_extensions/libsecret.py", line 34, in
gi.require_version("Secret", "1") # Would require a package gir1.2-secret-1
File "/home/trusted-service-user/cluster-env/env/lib/python3.8/site-packages/gi/init.py", line 126, in require_version
raise ValueError('Namespace %s not available' % namespace)
ValueError: Namespace Secret not available
SharedTokenCacheCredential.get_token failed: Shared token cache unavailable
VisualStudioCodeCredential.get_token failed: Failed to get Azure user details from Visual Studio Code.
AzureCliCredential.get_token failed: Azure CLI not found on path
DefaultAzureCredential failed to retrieve a token from the included credentials.
Attempted credentials:
EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.
SharedTokenCacheCredential: Shared token cache unavailable
VisualStudioCodeCredential: Failed to get Azure user details from Visual Studio Code.
AzureCliCredential: Azure CLI not found on pathClientAuthenticationError Traceback (most recent call last)
/tmp/ipykernel_7117/2959706531.py in
1 prompt = "Once upon a time"
2
----> 3 response = get_completion(
4 prompt=prompt,
5 temperature=0.7,/tmp/ipykernel_7117/1869397622.py in get_completion(**kwargs)
13 def get_completion(**kwargs):
14 # Refresh token
---> 15 refresh_token()
16 # Set the API key to be your Bearer token (yes this could be optimizaed to not do this every time :D)
17 openai.api_key = token.token/tmp/ipykernel_7117/1869397622.py in refresh_token()
8 # Check if Azure token is still valid
9 if not token or datetime.datetime.fromtimestamp(token.expires_on) < datetime.datetime.now():
---> 10 token = default_credential.get_token("https://cognitiveservices.azure.com")
11 print(token)
12
~/cluster-env/env/lib/python3.8/site-packages/azure/identity/_credentials/default.py in get_token(self, *scopes, **kwargs)
142 return token
143
---> 144 return super(DefaultAzureCredential, self).get_token(*scopes, **kwargs)~/cluster-env/env/lib/python3.8/site-packages/azure/identity/_credentials/chained.py in get_token(self, *scopes, **kwargs)
88 message = self.class.name + " failed to retrieve a token from the included credentials." + attempts
89 _LOGGER.warning(message)
---> 90 raise ClientAuthenticationError(message=message)ClientAuthenticationError: DefaultAzureCredential failed to retrieve a token from the included credentials.
Attempted credentials:
EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.
SharedTokenCacheCredential: Shared token cache unavailable
VisualStudioCodeCredential: Failed to get Azure user details from Visual Studio Code.
AzureCliCredential: Azure CLI not found on path
解决方案
1. 修正角色分配对象
此前给AML Workspace本身分配Cognitive Services User角色的对象错误,需将该角色分配给以下任一主体:
- 运行Notebook的Compute Instance系统托管标识
- 你的Azure AD用户账户(若通过交互式方式登录AML Workspace)
操作步骤:
- 进入Azure OpenAI资源的**访问控制(IAM)**页面
- 点击添加角色分配,选择Cognitive Services User角色
- 在成员页签选择对应主体:搜索Compute Instance名称(托管标识)或你的用户名(用户账户),完成分配
2. 适配AML环境的认证逻辑
在AML Workspace中运行Notebook时,推荐使用AzureMLWorkspaceCredential获取token,它会自动复用当前AML会话的身份(用户身份或托管标识)。修改refresh_token函数中的凭证初始化代码:
from azure.identity import AzureMLWorkspaceCredential from azureml.core import Workspace # 自动加载当前AML Workspace配置 ws = Workspace.from_config() default_credential = AzureMLWorkspaceCredential(workspace=ws)
若坚持使用DefaultAzureCredential,可排除无需的凭证源,规避本地依赖问题:
from azure.identity import DefaultAzureCredential, ExcludeCredential default_credential = DefaultAzureCredential( exclude_shared_token_cache_credential=True, exclude_visual_studio_code_credential=True, exclude_azure_cli_credential=True )
3. 验证托管标识状态
若使用Compute Instance托管标识,需确认其已启用系统分配标识:
- 进入AML Workspace的计算页面,选中目标Compute Instance
- 切换至标识标签页,确认系统分配状态为已启用
4. 临时修复依赖问题(可选)
若仍出现gir1.2-secret-1相关错误,可在Notebook中执行以下命令安装依赖(仅适用于Linux Compute Instance):
!sudo apt-get update && sudo apt-get install -y gir1.2-secret-1
内容的提问来源于stack exchange,提问作者Manu Chadha

