Skip to main content
 首页 » 编程设计

python之如何在没有 UI 交互的情况下使用 python 连接 Microsoft Graph

2024年09月07日31fff_TT

我正在关注此链接> 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 , client secret 不被 acquire_token_with_username_password 方法接受,所以你需要注册 native app.

示例代码:

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。

希望对你有帮助。