You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python通过Direct Line向Azure Bot发消息:托管身份无密码报错

问题解决方案

核心问题:MicrosoftAppCredentials依赖应用密码生成令牌,但用户分配托管身份无应用密码,需改用Azure Identity SDK实现托管身份认证逻辑。

1. 补充安装依赖包

安装用于托管身份令牌获取的Azure SDK包:

pip install azure-identity

2. 替换凭证逻辑,使用托管身份获取令牌

自定义凭证类继承MicrosoftAppCredentials,通过Azure Identity获取Direct Line服务的合法令牌:

from botframework.connector.auth import MicrosoftAppCredentials
from botframework.connector.client import ConnectorClient
from azure.identity import DefaultAzureCredential

class ManagedIdentityAppCredentials(MicrosoftAppCredentials):
    def __init__(self, client_id):
        super().__init__(client_id, "")
        self.client_id = client_id
        self.credential = DefaultAzureCredential(managed_identity_client_id=client_id)

    async def get_access_token(self, force_refresh=False):
        # Direct Line服务的令牌受众范围
        scope = "https://directline.botframework.com/.default"
        token = self.credential.get_token(scope)
        return token.token

# 替换为你的用户分配托管身份Client ID
CLIENT_ID = "YOUR_USER_ASSIGNED_MANAGED_IDENTITY_CLIENT_ID"
# 替换为实际对话ID和消息内容
CONVERSATION_ID = "YOUR_CONVERSATION_ID"
MESSAGE = {
    "type": "message",
    "text": "Hello from managed identity!"
}

credentials = ManagedIdentityAppCredentials(CLIENT_ID)
base_url = "https://directline.botframework.com/"

client = ConnectorClient(credentials, base_url=base_url)
client.conversations.send_to_conversation(CONVERSATION_ID, MESSAGE)

3. 关键配置检查

  • Azure环境运行:确保应用所在Azure资源(App Service/VM/Function等)已启用用户分配托管身份,并关联目标托管身份。
  • 本地测试:通过az login登录有权限使用该托管身份的Azure账号,或设置环境变量AZURE_CLIENT_ID为托管身份Client ID。
  • 权限配置:在Azure AD中为用户分配托管身份添加https://directline.botframework.com的相关权限(如DirectLine.Send)。

内容的提问来源于stack exchange,提问作者GLP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 20:35:17