我正在尝试使用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请求以获取访问令牌,因此可以很好地解析Requests JSON主体。我也尝试过在JSON有效负载中使用单引号或双引号,但它也不起作用。
我的看法是Graph API误解了某些内容,但我不知道是什么。
感谢您的帮助!
我找到了解决方案。我没有将数据参数传递给request.post方法,而是传递了json =参数
response = requests.post(
'https://graph.microsoft.com/v1.0/invitations'
, json={'invitedUserEmailAddress':email,'inviteRedirectUrl':'https://myapp.com'}
, headers = req_headers
)