gpt4 book ai didi

c# - 使用 .NET 5 调用受 Azure B2C 保护的 Web API

转载 作者:行者123 更新时间:2023-12-03 03:46:33 27 4
gpt4 key购买 nike

我正在尝试调用受 Azure B2C 保护的 Web API。我正在使用 .NET 5。我还使用 Azure B2C 来保护我的 WebApp。

在我的 WebApp startup.cs 中,我有:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddDownstreamWebApi("API", Configuration.GetSection("AzureB2API"))
.AddInMemoryTokenCaches();

我正在使用 ITokenAcquisition 来获取访问 token 。我尝试了 IDownstreamWebApi,但没有成功。

string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(Scopes);

我遇到的问题是,我收到的访问 token 的版本是版本 1。但是,Web API 需要版本 2。

我尝试将 Azure B2C WebAPI list 中的版本更改为 1 (accessTokenAcceptedVersion),但它不接受更改。

任何建议将不胜感激。

Web API的startup.cs是:

services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd");

最佳答案

请检查以下是否可以解决。

AddInMemoryTokenCaches 添加内存 token 缓存提供程序,它将缓存为下游 Web API 获取的访问 token 。

services.AddMicrosoftIdentityWebAppAuthentication(Configuration,"AzureAdB2C").EnableTokenAcquisitionToCallDownstreamApi(new string[] { Configuration["TodoList:TodoListScope"] }).AddInMemoryTokenCaches();services.AddInMemoryTokenCaches();

因此,您可以在更改接受的版本后清除缓存,以便应用程序不会采用之前缓存和使用的版本,直到它过期为止。 reference1

正如您提到的,Web API 需要版本 2,我认为您可能必须在调用门户中的 Web API 的 Azure B2C WebAPP list 中将 accessTokenAcceptedVersion 更改为 2。

"accessTokenAcceptedVersion": 2,

Note

  1. If the value of Supported account types is Accounts in anyorganizational directory and personal Microsoft accounts (e.g.Skype, Xbox, Outlook.com), the accepted token version must be v2.0.
  2. Otherwise, the accepted token version can be v1.0
  3. If the value is 2, the web API accepts v2.0 tokens.
  4. If the value is null, the web API accepts v1.0 tokens.

其他要点:另请检查范围和权限 Protected web API app registration

/ The ASP.NET core templates are currently using Azure AD v1.0, andcompute // the authority (as {Instance}/{TenantID}). We want to usethe Microsoft Identity Platform v2.0 endpoint
options.Authority =options.Authority + "/v2.0/";

另请参阅this

关于c# - 使用 .NET 5 调用受 Azure B2C 保护的 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68956264/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com