使用Python进行Microsoft Graph身份验证

huangapple go评论73阅读模式
英文:

Authenticate to Microsoft Graph with Python

问题

我从微软开发者页面下载了脚本,以在 Python 和 Microsoft Graph API 之间建立连接。这运行良好。

如果我启动脚本,每次都必须进行身份验证。在 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 进行身份验证。

英文:

I downloaded the script from the mcirsoft developer page to get a connection between python and the mcirosoft graph api. This works fine. (https://developer.microsoft.com/en-us/graph/quick-start)

If I start the script I have to authenticate every time. In the Python Console it says following text:

> To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code DY73DDLYA to authenticate.

The Python function for authentication is this:

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)

How can I authenticate only once?
I have the authentication already in the config file.

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

I expected the credentials are enough to authenticate to Azure.

答案1

得分: 1

你可以始终使用此模板使用Python获取访问令牌。

确保在系统中安装这些模块 `pip install requests, msal`
使用从Azure AD中的应用程序注册检索到的信息替换 `tenantID, clientID 和 clientsecret`

import msal
import json
import requests

def get_access_token():
tenantID = 'xxx' # 替换为你的
authority = 'https://login.microsoftonline.com/' + tenantID
clientID = 'xxx' # 替换为你的
clientSecret = 'xxx' # 替换为你的
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

令牌块

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


然后,您可以像这样进行API调用

例如,使用Graph API返回所有用户

构建Microsoft Graph API的URL

返回租户中的所有用户:

url = "https://graph.microsoft.com/v1.0/users/"

设置API调用的标头

headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}

发送API请求并获取响应

response = requests.get(url, headers=headers)

将响应解析为JSON

data = json.loads(response.text)
print(data)


这个解决方案不要求您始终对设备进行身份验证等等....希望对您有所帮助。
英文:

you can always use this template to get access token using python.

make sure to install this modules in your system pip install requests, msal
Replace 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)

Then you can make API calls likes this

For example to returns all my users using graph 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)

This solution does not require you to always authenticate device etc....I hope it helps.

huangapple
  • 本文由 发表于 2023年3月7日 21:06:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定