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

如何在WPF应用中通过托管身份连接Azure App Configuration?

在WPF中通过MSAL令牌连接Azure App Configuration的实现

不需要额外引入核心库,你可以借助Azure.Identity包中的适配类,或者自定义TokenCredential对接已有的MSAL认证逻辑,完成和Azure App Configuration的连接。

准备工作

确保项目已安装以下NuGet包:

  • Microsoft.Identity.Client(你已在使用)
  • Azure.Data.AppConfiguration(用于操作配置)
  • Azure.Identity(提供TokenCredential相关实现)

方案一:用MsalTokenCredential直接对接MSAL客户端

Azure.Identity中的MsalTokenCredential可直接接收你的IPublicClientApplication实例,自动处理令牌的获取与刷新,无需手动管理令牌生命周期:

// 初始化你的IPublicClientApplication(复用现有代码)
var identityClient = PublicClientApplicationBuilder
    .Create("你的客户端ID")
    .WithRedirectUri("msal{你的客户端ID}://auth")
    .Build();

// 创建MsalTokenCredential,指定App Configuration的权限范围
var credential = new MsalTokenCredential(identityClient, new[] { "https://azconfig.io/.default" });

// 初始化ConfigurationClient
var client = new ConfigurationClient(new Uri("https://xxx.azconfig.io"), credential);

// 示例:读取配置值
var setting = await client.GetConfigurationSettingAsync("你的配置键");
Debug.WriteLine(setting.Value);

方案二:基于已获取的令牌自定义TokenCredential

如果要复用已写好的MSAL认证逻辑,可自定义TokenCredential实现,直接返回已获取的令牌:

public class CustomMsalCredential : TokenCredential
{
    private readonly AuthenticationResult _authResult;

    public CustomMsalCredential(AuthenticationResult authResult)
    {
        _authResult = authResult;
    }

    public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
    {
        return new AccessToken(_authResult.AccessToken, _authResult.ExpiresOn);
    }

    public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
    {
        return ValueTask.FromResult(new AccessToken(_authResult.AccessToken, _authResult.ExpiresOn));
    }
}

在你的认证代码后使用自定义凭证:

// 你的现有认证逻辑,获取result1
var accounts = await IdentityClient.GetAccountsAsync();
AuthenticationResult? result1 = null;

try
{
    result1 = await IdentityClient
        .AcquireTokenSilent(Constants.Scopes, accounts.FirstOrDefault())
        .ExecuteAsync();
}
catch (MsalUiRequiredException)
{
    result1 = await IdentityClient
        .AcquireTokenInteractive(Constants.Scopes)
        .ExecuteAsync();
}
catch (Exception ex)
{
    Debug.WriteLine($"Error: Authentication failed: {ex.Message}");
}

// 验证令牌有效后,创建客户端
if (result1 != null)
{
    var customCredential = new CustomMsalCredential(result1);
    var client = new ConfigurationClient(new Uri("https://xxx.azconfig.io"), customCredential);
    
    // 后续配置操作
}

关键注意事项

  • 确保Constants.Scopes包含Azure App Configuration的权限范围:https://azconfig.io/.default
  • 在Azure门户中,给当前认证用户分配App Configuration Data Reader(或更高权限)角色,确保用户有权读取配置内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:23:28