要实现“不需要每次刷新授权就调用Microsoft Graph API”的解决方法,可以使用Microsoft的MSAL库(Microsoft Authentication Library)来管理身份验证和令牌刷新。
下面是一个使用MSAL库的代码示例:
import requests
import msal
# 定义应用程序的客户端ID、秘密和范围
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
scope = ['User.Read']
# 创建一个MSAL应用程序对象
app = msal.ConfidentialClientApplication(
client_id,
client_credential=client_secret,
authority='https://login.microsoftonline.com/your-tenant-id'
)
# 获取访问令牌
result = app.acquire_token_silent(scope, account=None)
if not result:
# 如果没有缓存的令牌,则需要进行交互式身份验证
result = app.acquire_token_interactive(scope)
if "access_token" in result:
# 使用访问令牌调用Microsoft Graph API
access_token = result['access_token']
headers = {
'Authorization': 'Bearer {0}'.format(access_token),
'Content-Type': 'application/json'
}
response = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers)
print(response.json())
else:
print(result.get("error"))
print(result.get("error_description"))
上述代码中,首先创建了一个MSAL应用程序对象,并指定了客户端ID、秘密和权限范围。然后,通过调用acquire_token_silent
方法从缓存中获取访问令牌。如果缓存中没有令牌,就调用acquire_token_interactive
方法进行交互式身份验证。
最后,如果成功获取到访问令牌,就可以使用该令牌作为Bearer令牌,将其附加到HTTP请求的Authorization头中,调用Microsoft Graph API。
注意:在实际应用中,需要替换代码中的YOUR_CLIENT_ID
、YOUR_CLIENT_SECRET
和your-tenant-id
为实际的值。另外,还需要根据实际需求修改权限范围和API调用的细节。