Fab*_*gas 5 python oauth-2.0 outlook-restapi office365api
我的用例是:制作一个每小时运行一次的脚本,以提取有关用户日历的信息。
我的脚本在 Python 中运行,我获得了一个令牌,但我无法获得用户的事件。我已在Microsoft 应用程序注册门户中注册了我的应用程序并授予了 Calendar.read 应用程序权限。管理员通过访问/adminconsent端点表示同意。
这是我获取令牌的代码(此处为文档):
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')
Run Code Online (Sandbox Code Playgroud)
我应该使用什么范围?文档只提到了上面的一个。
并阅读用户的日历:
url = 'https://outlook.office.com/api/v2.0/users/{}/events'.format(user_email)
headers = {
'Authorization': 'Bearer {}'.format(token)
}
r = requests.get(url, headers=headers)
Run Code Online (Sandbox Code Playgroud)
我不确定那 users/{user_email}/部分。
我获得了访问令牌,但在尝试读取用户的日历时出现以下错误:
响应 [401]
访问令牌是使用太弱而无法访问此应用程序的身份验证方法获取的。提供的身份验证强度为 1,要求为 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)
Run Code Online (Sandbox Code Playgroud)
微软的文档确实需要澄清。它有太多不同的 API 做着非常相似的事情。
| 归档时间: |
|
| 查看次数: |
14266 次 |
| 最近记录: |