python - 如何使用python连接Microsoft Graph而不需要UI交互?

标签 python azure microsoft-graph-api

我正在关注此链接> python-sample-send-mail发送电子邮件,但我想在后台跳过或验证用户而不进行任何 UI 交互。我不喜欢 OAuth: 弹出窗口的想法。

我的应用程序已在 Microsoft Azure AD 中注册。

我想知道如何在没有 UI 交互的情况下使用电子邮件用户名和密码进行身份验证。

非常感谢!

最佳答案

基于文档:AAD V2.0 end pointRestrictions on protocols , The OAuth 2.0 Resource Owner Password Credentials Grant v2.0 端点不支持。

python ADAL sdk ,acquire_token_with_username_password方法不接受客户端 key ,因此您需要注册native应用程序。

示例代码:

import adal
import requests

tenant = ""
client_id = "app id"
# client_secret = ""

username = ""
password = "”

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_test',
'Authorization' : 'Bearer {0}'.format(token["accessToken"]),
'Accept' : 'application/json',
'Content-Type' : 'application/json'
}

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

此外,如果使用REST API,则不需要原生应用,但需要设置client Secret

enter image description here

希望对您有帮助。

关于python - 如何使用python连接Microsoft Graph而不需要UI交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566175/

相关文章:

Azure 流分析 - 比较当前事件温度级别是否与先前事件温度级别相同

microsoft-graph-api - 无法获取 WAC 访问 token

firebase-authentication - 使用Microsoft Azure/Graph的Firebase自定义Auth

azure - 为什么 Azure AD Graph API 可能仍然比 Microsoft Graph API 更合适

python - pip:将依赖项下载到特定平台,包括非二进制文件

azure - 已验证的开放 API 规范无法上传到 Azure API 管理

Python - 以 numpy datetime64 格式获取当前时间

asp.net-mvc - ASP.NET MVC 与 Azure B2C 刷新 ID token 问题

python - 使用正则表达式在句子中查找单词

python - 如何在 python 中模拟 biased die?