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

如何为Default Azure Credential指定多组应用设置以调用不同API

问题解答

可以在Azure环境中指定DefaultAzureCredential读取的应用设置,也可以直接使用更适配多凭据场景的特定凭据类来实现,以下是两种可行方案:

方案一:通过DefaultAzureCredentialOptions指定自定义凭据参数

你可以在实例化DefaultAzureCredential时,通过DefaultAzureCredentialOptions手动传入目标应用注册的信息(从自定义应用设置键读取),覆盖默认的环境变量读取逻辑:

public async Task<string> GetTokenForAnotherApi(IConfiguration configuration)
{
    // 从自定义应用设置中读取另一组凭据信息
    var targetClientId = configuration["ANOTHER_API_CLIENT_ID"];
    var targetTenantId = configuration["ANOTHER_API_TENANT_ID"];
    var targetClientSecret = configuration["ANOTHER_API_CLIENT_SECRET"];
    var scope = $"{targetClientId}/.default";

    var options = new DefaultAzureCredentialOptions
    {
        ClientId = targetClientId,
        TenantId = targetTenantId,
        // 指定优先使用目标ClientSecretCredential,避免其他凭据源干扰
        CredentialChain = new List<TokenCredential>
        {
            new ClientSecretCredential(targetTenantId, targetClientId, targetClientSecret)
        }
    };

    DefaultAzureCredential credential = new DefaultAzureCredential(options);
    var accessToken = await credential.GetTokenAsync(new TokenRequestContext(scopes: new[] { scope }));

    return accessToken.Token;
}

方案二:直接使用ClientSecretCredential(更简洁)

如果不需要DefaultAzureCredential的多凭据链能力,直接实例化ClientSecretCredential并传入自定义配置参数,是更高效的方式:

public async Task<string> GetTokenForAnotherApi(IConfiguration configuration)
{
    var targetClientId = configuration["ANOTHER_API_CLIENT_ID"];
    var targetTenantId = configuration["ANOTHER_API_TENANT_ID"];
    var targetClientSecret = configuration["ANOTHER_API_CLIENT_SECRET"];
    var scope = $"{targetClientId}/.default";

    var credential = new ClientSecretCredential(targetTenantId, targetClientId, targetClientSecret);
    var accessToken = await credential.GetTokenAsync(new TokenRequestContext(scopes: new[] { scope }));

    return accessToken.Token;
}

应用设置配置说明

在Azure函数应用的配置面板中,添加以下自定义键值对:

  • ANOTHER_API_CLIENT_ID:目标API对应的Entra ID应用注册Client ID
  • ANOTHER_API_TENANT_ID:目标API对应的租户ID
  • ANOTHER_API_CLIENT_SECRET:目标API对应的应用密钥

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 09:02:19