【问题标题】:MS Graph authentication using python使用 python 的 MS Graph 身份验证
【发布时间】:2017-03-20 17:48:48
【问题描述】:

尝试编写一个 Python 代码,我想在其中访问我的日历并检索我的日程安排。 无法通过身份验证阶段。 看过并测试了许多示例,但都需要运行本地服务器,我在本地浏览并需要单击按钮然后输入我的凭据。 旨在在我的 Python 代码中执行所有这些操作。

【问题讨论】:

  • 您应该在问题中包含更多详细信息。到目前为止您尝试过的示例代码、正在发生的屏幕截图/错误以及您期望的详细信息。查看 StackOverflow 的提问指南:stackoverflow.com/help/how-to-ask
  • 假设在我的 Python 代码中,我正在形成这种链接,带有重定向 URI 和客户端 ID:login.microsoftonline.com/common/oauth2/…> 这将导致需要输入我的云凭据的响应。我想在没有人为干预的情况下做到这一点,即从 Python 代码中。

标签: python office365 microsoft-graph-api


【解决方案1】:

您可以通过以下两种方式之一来实现:

  1. 使用 资源所有者密码凭据流 - 这允许您将用户名和密码传递给 Azure AD。如果身份验证流程中有任何额外内容(同意、MFA、密码重置),您就会遇到问题。
  2. 使用客户端凭据流 - 这需要admin consent。此外,您必须非常小心这一点,因为该客户端将有权访问有关所有用户的所有信息。这只应与安全客户端一起使用,而不应与其他用户有权访问的客户端一起使用。

这里有一个代码 sn-p 展示了这两个:

import adal
import requests

tenant = "contoso.com"
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"

username = "foo@contoso.com"
password = "mypassword"

authority = "https://login.microsoftonline.com/" + tenant
RESOURCE = "https://graph.microsoft.com"

context = adal.AuthenticationContext(authority)

# Use this for Client Credentials
#token = context.acquire_token_with_client_credentials(
#    RESOURCE,
#    client_id,
#    client_secret
#    )

# Use this for Resource Owner Password Credentials (ROPC)  
token = context.acquire_token_with_username_password(RESOURCE, username, password, client_id);

graph_api_endpoint = 'https://graph.microsoft.com/v1.0{0}'

# /me only works with ROPC, for Client Credentials you'll need /<UsersObjectId/
request_url = graph_api_endpoint.format('/me')
headers = { 
'User-Agent' : 'python_tutorial/1.0',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}

response = requests.get(url = request_url, headers = headers)
print (response.content)

【讨论】:

  • 终于!在 Azure AD 中注册应用程序后,“客户端 ID/客户端密码”路由对我有效。
  • ROPC 流程中的consent 是什么?我有管理员权限,如果需要,我应该在哪里同意?
【解决方案2】:

将尝试上述...

我用这个例子来解决这个问题 - https://developer.microsoft.com/en-us/graph/docs/authorization/app_only

问题是在 Azure 中为应用请求正确的权限。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-19
    • 2021-01-10
    • 2021-07-23
    • 2018-12-02
    • 2021-09-14
    • 1970-01-01
    • 2022-08-23
    • 2019-08-16
    相关资源
    最近更新 更多