我的用例是:创建一个每小时运行一次的脚本,以提取有关用户日历的信息。
我的脚本在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}/
部分。
我获得了访问令牌,但在尝试阅读用户日历时出现以下错误:
回应[401]
使用身份验证方法获取访问令牌,该身份验证方法太弱而无法访问此应用程序。提出的auth强度为1,要求为2.
答案 0 :(得分:2)
我终于找到了它。我很亲密。
我不得不使用Microsoft Graph API端点而不是Outlook Unified 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,可以做很多类似的事情。