【问题标题】:Authentication in Outlook 365 apiOutlook 365 api 中的身份验证
【发布时间】:2018-02-25 19:17:21
【问题描述】:

我的用例是:制作一个每小时运行一次的脚本,以提取有关用户日历的信息。

我的脚本在 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]

访问令牌是使用一种太弱的身份验证方法获取的,该方法不允许此应用程序访问。提交的身份验证强度为 1,要求为 2。

【问题讨论】:

    标签: python oauth-2.0 office365api outlook-restapi


    【解决方案1】:

    我终于找到了。我非常接近。

    我不得不使用 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)
    

    Microsoft 的文档确实需要澄清。它有太多不同的 API 来做非常相似的事情。

    【讨论】:

    • 感谢Fabrice 的反馈。 Graph 绝对是推荐使用的 API。它实际上在幕后使用了 Outlook 端点。我们这里有一个文档试图解释差异以及为什么您可能会选择其中一个:docs.microsoft.com/en-us/outlook/rest/compare-graph-outlook。我们正在努力统一 REST API 故事,以明确 Graph 是首选方式。
    • 酷。感谢您的评论。我想这是您尝试从一个版本转换到另一个版本的时间点,因此我的最后一句话。
    • 我完全同意你对微软文档的失望。没有简单的python例子,只有Django服务器搭建教程……
    • app_id 是您的用户名? client_secret 是你的密码?
    • @partydog 嗯不?不知道你说的用户名和密码是什么意思。但据我记得,在您的 Microsoft Graph Web 视图中,您可以获取应用程序标识符(在我的示例中为 app_id)并生成要在代码中使用的密钥(client_secret)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2017-07-24
    • 2019-08-16
    相关资源
    最近更新 更多