You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python azure-identity库的ClientSecretCredential获取Azure服务访问令牌时的Scope参数配置疑问

How to Set the Scope Parameter for ClientSecretCredential in azure-identity (Python)

I totally get the confusion here—switching from the older ADAL library (used in your C# code) to MSAL-based azure-identity in Python means shifting from a "resource" parameter to a "scope" parameter, and it's not immediately obvious how they map. Let's break this down:

The Core Difference: ADAL vs. MSAL

Your C# code uses AcquireTokenAsync(aasUrl, clientCred) where aasUrl is the resource you want to access. ADAL (Azure Active Directory Authentication Library) relies on this resource value. But Python's azure-identity is built on MSAL (Microsoft Authentication Library), which uses scopes instead—and the format requires a small tweak to your original resource URL.

Convert Your Resource to a Valid Scope

For the client credential flow (which you're using with client ID/secret), you just need to append /.default to the end of your original aasUrl value. This suffix tells Azure AD to issue a token using all the application-level permissions you've already configured for your app registration.

Corrected Python Code Example

Here's how to adjust your code to match the functionality of your working C# snippet:

from azure.identity import ClientSecretCredential

# Replace these with your actual values
tenant_id = "<your-tenant-id>"
client_id = "<your-app-id>"
client_secret = "<your-app-secret>"
aas_url = "<your-aas-url>"  # Same as the aasUrl variable in your C# code

authority = f"https://login.microsoftonline.com/{tenant_id}"
credential = ClientSecretCredential(tenant_id, client_id, client_secret, authority=authority)

# Convert the resource URL to a valid scope for client credential flow
scope = f"{aas_url}/.default"
token = credential.get_token(scope)

# Access the token string
print(token.token)

Why /.default Works

The /.default suffix is specific to non-interactive flows like client credentials. It signals Azure AD to use all the application permissions you've granted to your registered app (configured in the Azure Portal under "API permissions"). This is exactly equivalent to how your C# code uses the resource parameter—no user interaction is required, just the app's own credentials.

If you haven't already, make sure to add the relevant API permissions for your target Azure service (e.g., Azure Analysis Services) to your app registration and grant admin consent for them.

内容的提问来源于stack exchange,提问作者SCOUT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:08:14