从Azure Bot向Skype用户发消息时遇Invalid JWT错误求助
我在尝试从Azure Bot向Skype用户发送非回复消息时,遇到了“Invalid JWT”错误,尽管使用的似乎是有效的令牌。具体情况如下:
- 已通过Microsoft Bot Framework的OAuth客户端凭据成功生成访问令牌。
- 已成功创建会话ID,但使用该ID发送消息时,收到带有“Invalid JWT”的401错误。
相关代码
令牌生成配置
import requests # Setup for token generation service_url = "https://smba.trafficmanager.net/apis" token_url = f'https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token' token_headers = {'Content-Type': 'application/x-www-form-urlencoded'} token_payload = { 'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_password, 'scope': 'https://api.botframework.com/.default' }
请求令牌
token_response = requests.post(token_url, headers=token_headers, data=token_payload) token = token_response.json()['access_token']
创建会话
conversation_headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'} conversation_url = f"{service_url}/v3/conversations" conversation_payload = { "bot": {"id": f"28:{app_id}", "name": "botname"}, "isGroup": False, "members": [{"id": skype_id, "name": "Milkiyas Gebru"}], "topicName": "New Conversation" } conversation_response = requests.post(conversation_url, headers=conversation_headers, json=conversation_payload) conversation_id = conversation_response.json()["id"]
发送消息
message_url = f"{service_url}/v3/conversations/{conversation_id}/activities" message_headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'} message_payload = {"type": "message", "text": "My bots reply"} message_response = requests.post(message_url, headers=message_headers, json=message_payload) print("Create Message Response: ",message_response.json(), message_response.status_code)
错误响应
Create Message Response: {'error': {'code': 'AuthorizationError', 'message': 'Invalid JWT.'}} 401
请问是什么导致JWT被判定为无效?有什么解决建议?
检查令牌有效期
创建会话成功不代表发送消息时令牌仍有效,JWT通常有较短的有效期。可以解码令牌查看过期时间:import jwt decoded_token = jwt.decode(token, options={"verify_signature": False}) print("Token expires at:", decoded_token['exp'])建议在发送消息前重新获取令牌,避免过期问题。
调整权限范围
对于Skype渠道,仅使用https://api.botframework.com/.default可能权限不足,尝试添加Skype专属范围:'scope': 'https://api.botframework.com/.default https://api.skype.com/.default'验证Bot ID格式
确认bot.id中的app_id是纯应用ID,无额外前缀或字符。部分渠道对Bot ID格式有严格要求,错误格式可能导致后续请求授权失败。检查令牌受众
解码令牌查看aud字段,确认其值为https://api.botframework.com。若受众不匹配,说明令牌请求的scope配置错误,需修正。确认会话ID正确性
打印conversation_id确认格式符合要求(通常为19:xxx@thread.skype;messageid=xxx),避免提取时引入多余空格或字符。更换区域专属端点
若Bot部署在特定区域,通用的smba.trafficmanager.net可能不适用,需替换为对应区域的服务端点,比如中国区域使用smba.trafficmanager.net/apac/apis。
内容的提问来源于stack exchange,提问作者Milkiyas Holitech

