Outlook 365 API - 身份验证
问题描述:
我有一个绝对可怕的时间试图使用Outlook 365 API。我的用例非常简单:制作一个脚本,每小时运行一次,以提取有关用户日历的信息。Outlook 365 API - 身份验证
我的脚本在Python中运行,我能够获得一个令牌,但我无法获取用户的事件。我明显在Microsoft Application Registration Portal中注册了我的应用程序,并获得了Calendar.read应用程序权限。管理员还通过访问/adminconsent
端点进行了同意。
这里是我的代码,以获得令牌(文档here):
url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
data = {
'grant_type': 'client_credentials',
'client_id': app_id,
'scope': 'https://graph.microsoft.com/.default', <--- Really not sure about this here
'client_secret': client_secret,
}
r = requests.post(url, data=data)
token = r.json().get('access_token')
是我该什么范围使用?该文件只提到以上的文件。
,并读取用户的日历:
url = 'https://outlook.office.com/api/v2.0/users/{}/events'.format(user_email)
headers = {
'Authorization': 'Bearer {}'.format(token)
}
r = requests.get(url, headers=headers)
同样,我真的不知道该users/{user_email}/
部分。我阅读了一些关于stackoverflow的人,他做了类似的事情,但在文档的任何地方找不到它。
我能够得到一个访问令牌,但我得到尝试读取用户的日历时出现以下错误:
响应[401]
的访问令牌使用的认证方法获取的太弱,无法访问此应用程序。提出的认证强度是1,要求是2.
请哦请stackoverflow,帮帮我。我花了太多的时间来完成这个非常简单的任务。
答
我终于找到它了。我非常接近。
我不得不使用Microsoft Graph API端点代替Outlook统一API端点。
最终的代码如下所示:
import requests
# Get a token
url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
data = {
'grant_type': 'client_credentials',
'client_id': app_id,
'scope': 'https://graph.microsoft.com/.default'
'client_secret': client_secret,
}
r = requests.post(url, data=data)
token = r.json().get('access_token')
# ...
# Use the token using microsoft graph endpoints
url = 'https://graph.microsoft.com/v1.0/users/{}/events'.format(user_email) # can also use the user_id (e.g. 12345-abcde-...)
headers = {
'Authorization': 'Bearer {}'.format(token)
}
r = requests.get(url, headers=headers)
微软的文档真的需要澄清。它有太多不同的API来做非常类似的事情。
感谢您的反馈Fabrice。 Graph绝对是推荐使用的API。它实际上使用封面下的Outlook端点。我们在这里有一个文档,试图解释不同之处以及为什么您可以选择一个:https://docs.microsoft.com/en-us/outlook/rest/compare-graph-outlook。我们正在努力将REST API的故事统一为超级清晰,Graph是首选方式。 –
很酷。感谢您的评论。我想那是你正试图从一个版本转换到另一个版本的那个时间点,因此是我最后一个短语。 –