使用Python获取Graph API访问令牌

问题描述 投票:0回答:1

我正在尝试复制获取 Web 上的 Microsoft Graph Explorer 中使用的访问令牌的实例。我查看了它提出的要求。我附上了从curl 转换为python 的以下内容。


import requests

headers = {
    'Accept': '*/*',
    'Accept-Language': 'en-GB,en;q=0.9',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Origin': 'https://developer.microsoft.com',
    'Pragma': 'no-cache',
    'Referer': 'https://developer.microsoft.com/',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'cross-site',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
    'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}

data = 'client_id=de8bc8b5-d9f9-48b1-a8ad-b748da725064&redirect_uri=https%3A%2F%2Fdeveloper.microsoft.com%2Fen-us%2Fgraph%2Fgraph-explorer&scope=openid%20profile%20User.Read%20offline_access&code=vW3k&x-client-SKU=msal.js.browser&x-client-VER=3.10.0&x-ms-lib-capability=retry-after, h429&x-client-current-telemetry=5|862,0,,,|,&x-client-last-telemetry=5|0|862,018f6224-a10e-73ae-b32d-a10aeab7b49b|user_cancelled|1,0&code_verifier=zpUdixfdLj4CsnhptxSZio&grant_type=authorization_code&client_info=1&client-request-id=018f6226-77e8-9028-ae2685da3b62&claims=%7B%22access_token%22%3A%7B%22xms_cc%22%3A%7B%22values%22%3A%5B%22CP1%22%5D%7D%7D%7D&X-AnchorMailbox=Oid%3A7aed27cb-3dd1-45d8-8323-7d0387be5ce0%4057c64fd4-66ca-49f5-ab38-2e67ef58e724'

response = requests.post('https://login.microsoftonline.com/common/oauth2/v2.0/token', headers=headers, data=data)

它使用以下有效负载:

client_id: de8bc8b5-d9f9-48b1-a8ad-b748da725064
redirect_uri: https://developer.microsoft.com/en-us/graph/graph-explorer
scope: openid profile User.Read offline_access
code: 0.AQYA1E_GV8pm9UmrOC5n71jnJLXIi9752bFIqK23SNpyUGQGAMQ.xxxx
x-client-SKU: msal.js.browser
x-client-VER: 3.10.0
x-ms-lib-capability: retry-after, h429
x-client-current-telemetry: 5|862,0,,,|,
x-client-last-telemetry: 5|0|862,018f6224-xxxx-xxxx-b32d-a10aeab7b49b|user_cancelled|1,0
code_verifier: zpUdixfdLxhmpxxxx
grant_type: authorization_code
client_info: 1
client-request-id: 018f6226-xxx-xxx-xxx-ae2685da3b62
claims: {"access_token":{"xms_cc":{"values":["CP1"]}}}
X-AnchorMailbox: Oid:7aed27cb-xxx-xxx-8323-7d0387be5ce0@57c64fd4-66ca-xxxx-xxxx-2e67ef58e724

这对我不起作用。它抛出一个错误。

b'{"error":"invalid_grant","error_description":"AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.
。如何在不使用刷新令牌的情况下动态获取访问令牌。我没有客户秘密。我的帐户上有 MFA,这意味着我需要通过输入显示的数字来批准我的 microsot 身份验证器的登录。

enter image description here

python azure-active-directory microsoft-graph-api
1个回答
0
投票

首先,使用“支持的帐户类型”注册一个多租户应用程序,如下所示:

enter image description here

要列出 SharePoint 站点中的项目,请确保在应用程序中分配“委派”类型的

Sites.Read.All
权限,如下所示:

enter image description here

为了避免在代码中使用客户端密钥,请确保在应用程序中启用 public client flow 选项,如下所示:

enter image description here

现在,使用以下示例 python 代码通过设备代码流获取 Graph API 访问令牌:

import msal

authority = "https://login.microsoftonline.com/common"
client_id = "appId"
scopes = ["Sites.Read.All"]

app = msal.PublicClientApplication(client_id=client_id, authority=authority)

result = None
flow = app.initiate_device_flow(scopes=scopes)
if "user_code" not in flow:
    print(flow.get("error"))
    print(flow.get("error_description"))
    raise ValueError("Couldn't create device flow")
else:
    print(flow["message"])
    result = app.acquire_token_by_device_flow(flow)

if "access_token" in result:
    access_token = result["access_token"]
    print("Access token acquired successfully:", access_token)
else:
    print(result.get("error"))
    print(result.get("error_description"))

当您运行代码示例时,它将显示一条带有链接和设备代码的消息,如下所示:

![enter image description here](https://i.imgur.com/wtZZV6h.png)

单击链接将打开浏览器并要求您输入设备代码,如下所示:

enter image description here

Next
步骤中,它会要求您使用Azure帐户登录,其中涉及MFA提示,如下所示:

enter image description here

身份验证成功后,您可以检查输出控制台,其中将生成访问令牌,如下所示:

enter image description here

为了确认这一点,您可以通过将其粘贴到 jwt.ms 网站并检查

scp
声明来解码此访问令牌:

enter image description here

当我通过运行下面的示例 python 代码来使用此令牌时,我得到了包含 SharePoint 站点中的项目列表的响应,如下所示:

import requests

access_token = 'your_access_token'
site_id = 'your_site_id'
list_id = 'your_list_id'

graph_endpoint = f"https://graph.microsoft.com/v1.0/sites/{site_id}/lists/{list_id}/items"

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

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

if response.status_code == 200:
    data = response.json()
    for item in data['value']:
        print(item)
else:
    print("Failed to retrieve items from SharePoint list.")
    print("Status code:", response.status_code)
    print("Response body:", response.text)

回复:

enter image description here

参考:

从 SharePoint 列表中检索项目 - Microsoft Graph v1.0

© www.soinside.com 2019 - 2024. All rights reserved.