python-requests - 使用请求在 Python 中邀请用户使用 Azure AD 时出现 Microsoft Graph“无法读取 JSON 请求有效负载”错误
问题描述
我正在尝试使用 MS Graph API 自动邀请用户加入 Azure AD,但出现“无法读取 JSON 请求有效负载”错误。
我正在从票务系统中提取数据,检索当前的 AAD 用户并对两者进行比较。然后我会将新的推送到 AAD 中并更新它们以将它们包含在与会者 AD 安全组中。
我创建了一个 Python Azure 函数,它使用 Requests 调用 Graph API:
def insert_users(users_emails):
logging.info('Inserting new users in AAD')
token = generate_auth_token()
users_emails = users_emails[:2]
added_attendees = []
for email in users_emails:
req_body = {
"invitedUserEmailAddress" : email
, "inviteRedirectUrl" : "https://myapp.com"
}
body_length = sys.getsizeof(req_body)
req_headers = {
'Authorization' : 'Bearer {0}'.format(token)
, 'Content-Type' : 'application/json; charset=utf-8'
, 'Content-Length' : str(body_length)
}
response = requests.post(
'https://graph.microsoft.com/v1.0/invitations'
, headers = req_headers
, data = req_body
)
response = response.json()
logging.info(response)
added_attendees.append(email)
return added_attendees
Graph API 发回以下错误消息:
{'error':
{'code': 'BadRequest',
'message': 'Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.',
'innerError':
{'request-id': '4ff5332d-d280-4b0d-9e04-a7359ab0e2fb', 'date': '2020-05-27T14:51:18'}
}
}
我尝试将字符集添加到 Content-Type 标头,但它不起作用。我在某个地方读到 Content-Length 可能有用,所以我也添加了它,但无济于事。
测试在 Postman 中运行正常,我已经对 Azure AD API 执行 POST 请求以获取访问令牌,因此请求 JSON 正文被解析得很好。我还尝试在 JSON 有效负载中使用单引号或双引号,但它也不起作用。
我的看法是 Graph API 误解了某些东西,但我不知道是什么。
感谢您的帮助!
解决方案
我找到了解决方案。我没有将 data 参数传递给 request.post 方法,而是传递了一个 json= 参数
response = requests.post(
'https://graph.microsoft.com/v1.0/invitations'
, json={'invitedUserEmailAddress':email,'inviteRedirectUrl':'https://myapp.com'}
, headers = req_headers
)
推荐阅读
- android - 在android模拟器上测试时出错
- reactjs - React REDUX 未将状态更新为新状态
- django - Django 模型中的 DateTimeField 列表
- python - 值在表格单元格处消失 - Python/pandastable
- react-native - 如何将 react-native-maps 绘制的地图当前状态分享到 google.com/maps?
- javascript - Connect4 与 P5.js 中的 MiniMax 算法
- gremlin - Neptune 在 Lambda 冷启动时返回 500 错误
- flutter - 与孩子一起放大堆栈
- android - Android:附件到电子邮件应用程序后何时删除文件?
- sql - 在 utl_mail.send 中传递电子邮件时出错 (Oracle 11g - sql) 06502 - 06512