微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Web 应用程序使用 Microsoft.Identity.Web 调用具有不同 ClientId 的多个 API

如何解决Web 应用程序使用 Microsoft.Identity.Web 调用具有不同 ClientId 的多个 API

我正在编写一个 Web 应用程序,它需要调用两个 API(OrderApi 和 ProductApi)。我需要在调用每个 Api 时传递不记名令牌。为每个 Api 生成不记名令牌的客户端 ID (AAD Id) 是不同的。我发现为这两个不同的客户端 ID 配置身份验证很困难。

AppSetting.json

" "

代码配置:

  "AzureAd1": {
    "Instance": "xxxxxxx","ClientId": "ClientId-1","TenantId": "xxxxx","ClientSecret": ""
  },"AzureAd2": {
    "Instance": "xxxxxxx","ClientId": "ClientId-2","ClientSecret": ""
  }

上述身份验证指的是 appsettings 中的“AzureAd1”,它将用于为 Order Api 生成不记名令牌。如何添加身份验证以读取“AzureAd2”设置并为 Prodcut Api 生成令牌?

调用 Web Api1:

        services.AddHttpClient<IOrderService,OrderService>(c =>
        {
            c.BaseAddress = new Uri("https://orderapitest.azurewebsites.net/");
            c.DefaultRequestHeaders.Add("Accept","application/vnd.github.v3+json");
            c.DefaultRequestHeaders.Add("User-Agent","HttpClientFactory-Sample");
        });

        services.AddHttpClient<IProductService,ProductService>(c =>
        {
            c.BaseAddress = new Uri("https://prodcutapitest.azurewebsites.net/");
            c.DefaultRequestHeaders.Add("Accept","HttpClientFactory-Sample");
        });

        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(appsettingsConfig,"AzureAd1")
            .EnabletokenAcquisitionToCallDownstreamApi(new string[] { "user.read" })
            .AddDownstreamWebApi("OrderApi",appsettingsConfig.GetSection("OrderApiUrl"))
            .AddInMemoryTokenCaches();

Web Api2:

public class OrderService : IOrderService
{
    private readonly HttpClient _httpClient;
    private readonly ITokenAcquisition _tokenAcquisition;

    public OrderService(HttpClient client,ITokenAcquisition tokenAcquisition)
    {
        this._httpClient = client;
        this._tokenAcquisition = tokenAcquisition;
    }

    public async Task<HttpResponseMessage> GetData(string requestUrl)
    {
        string[] scopes = new string[] { "user.read" };
        string accesstoken = await this._tokenAcquisition.GetAccesstokenForUserAsync(scopes);

        // Use the access token to call a protected web API.
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",accesstoken);

        return await httpClient.GetAsync($"{OrderApi}/Getorder");
    }
}

以上代码,OrderService 和 ProdcutService,使用“AzureAd1”设置生成不记名令牌。我希望 OrderService 应该使用“AzureAd1”和 ProdcutService 使用“AzureAd2”生成不记名令牌。 tokenAquisition 应该为相应的设置(clientid 和 secret)生成不记名令牌并调用 api。我该怎么做?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。