oauth2.0 使用Python验证Microsoft Graph

3b6akqbq  于 2023-03-17  发布在  Python
关注(0)|答案(1)|浏览(180)

我从mcirsoft开发者页面下载了这个脚本来获得python和mcirosoft图形API之间的连接。这个工作得很好。(https://developer.microsoft.com/en-us/graph/quick-start
如果我启动脚本,每次都要验证,在Python控制台中,它显示以下文本:
要登录,请使用Web浏览器打开页面https://microsoft.com/devicelogin,然后输入验证码DY73DDLYA进行身份验证。
用于验证的Python函数如下:

def initialize_graph_for_user_auth(config):
    this.settings = config
    client_id = this.settings['clientId']
    tenant_id = this.settings['authTenant']
    graph_scopes = this.settings['graphUserScopes'].split(' ')

    this.device_code_credential = DeviceCodeCredential(client_id, tenant_id = tenant_id)
    this.user_client = GraphClient(credential=this.device_code_credential, scopes=graph_scopes)

我怎样才能只认证一次?我已经在配置文件中有认证了。

[azure]
clientId = <CLIENT_ID>
clientSecret = <CLIENT_SECRET>
tenantId = <TENANT_ID>
authTenant = common
graphUserScopes = GroupMember.ReadWrite.All

我希望凭据足以向Azure进行身份验证。

mspsb9vt

mspsb9vt1#

你总是可以使用这个模板来获得使用python的访问令牌。
确保在您的系统中安装此模块pip install requests, msal替换tenantID, clientID and clientsecret with information retrieved from your app registration in azure AD

import msal
import json
import requests

def get_access_token():
    tenantID = 'xxx' #replace with yours
    authority = 'https://login.microsoftonline.com/' + tenantID
    clientID = 'xxx' # replace with yours
    clientSecret = 'xxx' # replace with yours
    scope = ['https://graph.microsoft.com/.default']
    app = msal.ConfidentialClientApplication(clientID, authority=authority, client_credential = clientSecret)
    access_token = app.acquire_token_for_client(scopes=scope)
    return access_token

# token block
access_token = get_access_token()
token = access_token['access_token']
print(token)

然后,您可以像这样进行API调用
例如,使用图形API返回我的所有用户

# Construct the URL for the Microsoft Graph API
# return all users in the tenant: 
url = "https://graph.microsoft.com/v1.0/users/"

# Set the headers for the API call
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

# Send the API request and get the response
response = requests.get(url, headers=headers)

# Parse the response as JSON
data = json.loads(response.text)
print(data)

这个解决方案确实需要你总是认证设备等....我希望它有帮助。

相关问题