使用 Web 应用以外的方式检索令牌

retrieve token other than with a web app

我遵循了这里的代码:

https://github.com/microsoftgraph/python3-connect-rest-sample

为了能够从没有 UI.

远程计算机访问我的 OneDrive 文件夹中的 excel 工作表

问题是我需要在我的机器上设置一个 flask 应用程序才能获得 access_token

特别是,这意味着我需要启动 flask 服务器,手动打开浏览器,导航到 http://localhost:5000,这将启动 OAuth 进程并检索令牌。然后,我将检索到的 access_token 发送到我可以继续工作的远程实例。

也许我可以用 selenium 使所有这些自动化,但我觉得这让事情过于复杂了。当然,必须有更好的方法以合理的方式做到这一点?

有两种方法可以获得令牌,无需 UI 提示输入用户名和密码且无需授权码:

  • 使用资源所有者密码凭据流 - 这允许您将用户名和密码传递给 Azure AD。问题是,如果身份验证流程中有任何额外的东西(同意、MFA、密码重置),你就会失败。
  • 使用客户端凭证流程 - 这需要管理员同意。另外,你必须非常小心这个,因为这个客户端可以访问所有用户的所有信息。这应该只用于安全客户端,而不是其他用户有权访问的客户端。

下面是展示这两者的代码片段:

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)

注意:我正在重复使用我对一个非常相似的问题的回答:MS Graph authentication using python