无法从msal python库获取访问令牌

问题描述 投票:0回答:1
from flask import Flask, jsonify, request, send_file
from flask_cors import CORS
import logging
from msal import ConfidentialClientApplication

app = Flask(__name__)
CORS(app)
# app.config['CORS_HEADERS'] = 'Content-Type'

client_id="d5869b9c-4266-secret"
client_secret="secret"
tenant_id="10f7b5eb-97cb-secret"

msal_authority = f"https://login.microsoftonline.com/{tenant_id}"

scopes = ['https://graph.microsoft.com/.default']

msal_app = ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=msal_authority)

result = msal_app.acquire_token_silent(
    scopes=scopes,
    account=None
)

if not result:
    result = msal_app.acquire_token_for_client(scopes=scopes)
    
if "access_token" is result:
    access_token = result['access_token']
else:
    raise Exception("No Access Token Found")
    
print("access token ==================> ", access_token)

Screen Shoot of app registration API Permission

我有一个使用 python 与 microsoft Graph API 连接的应用程序,但我需要访问令牌来执行请求。从上面的代码来看,我仍然无法从 msal 库获取访问令牌。有人可以指出我做错了什么吗?之前谢谢

python flask microsoft-entra-id msal
1个回答
0
投票

要通过应用程序连接 Microsoft Graph API,请使用

acquire_token_for_client
流。

  • acquire_token_silent
    用于从缓存中获取令牌(如果存在)。它用于以下场景:您有一个交互式用户会话,并且希望以静默方式获取新令牌而不再次提示用户。

我创建了一个 Microsoft Entra ID 应用程序并授予了 API 权限:

enter image description here

因此,要获取访问令牌,请修改如下代码:

from flask import Flask, jsonify, request
#from flask_cors import CORS
import logging
from msal import ConfidentialClientApplication

app = Flask(__name__)
#CORS(app)

client_id="ClientID"
client_secret="ClientSecret"
tenant_id="TenantID"

msal_authority = f"https://login.microsoftonline.com/{tenant_id}"

scopes = ['https://graph.microsoft.com/.default']

msal_app = ConfidentialClientApplication(
    client_id=client_id,
    client_credential=client_secret,
    authority=msal_authority
)

result = msal_app.acquire_token_for_client(scopes=scopes)

if "access_token" in result:
    access_token = result['access_token']
    print("Access token ==================> ", access_token)
else:
    raise Exception("No Access Token Found: " + result.get("error_description", "Unknown error"))

访问令牌已成功检索:

enter image description here

解码后显示角色:

enter image description here

使用上面生成的访问令牌,您可以调用 Microsoft Graph API。

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