如何将“AzureAd”详细信息显式传递给 AddMicrosoftIdentityWebApi 方法以进行令牌验证

sam*_*dar 7 c# access-token asp.net-identity asp.net-core microsoft-identity-platform

我正在使用Microsoft.Identity.Web库来验证 .Net Core Web API 中的令牌。

public void ConfigureServices(IServiceCollection services)
{
        ------------

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration);

        ------------
}
Run Code Online (Sandbox Code Playgroud)

但根据此处的文档,我需要通过 IConfiguration 实例将AzureAd(一个包含tenantId、ClientId、Domain、Instance 等的对象)对象传递给AddMicrosoftIdentityWebApi方法。截至目前,此方法尝试从本地 appsettings.json 文件加载此对象。我想将这些详细信息显式传递给该方法,AddMicrosoftIdentityWebApi因为我们没有在本地 appsettings.json 文件中存储任何键值(所有键值均来自 Consul 和 Vault)。

我尝试覆盖配置对象但无法做到。

如何将此 AzureAd 对象传递给AddMicrosoftIdentityWebApi方法,以便它可以验证令牌以及缺少什么?

更新:嘿..我设法显式传递这些值。

Action<JwtBearerOptions> configureJwtBearerOptions = Test1;
static void Test1(JwtBearerOptions t1)
{
    t1.Audience = $"{appSettings.adCredentials.Instance}/{appSettings.adCredentials.TenantId}";
    t1.TokenValidationParameters.ValidAudiences = new string[] {
        appSettings.adCredentials.ClientId,
        $"api://{appSettings.adCredentials.ClientId}"
    };
}

Action<MicrosoftIdentityOptions> configureMicrosoftIdentityOptions = Test2;
static void Test2(MicrosoftIdentityOptions t2)
{
    t2.TenantId = appSettings.adCredentials.TenantId;
    t2.ClientId = appSettings.adCredentials.ClientId;
    t2.Instance = appSettings.adCredentials.Instance;
    t2.Domain = appSettings.adCredentials.Domain;
    t2.ClientSecret = appSettings.adCredentials.ClientSecret;
}

IdentityModelEventSource.ShowPII = true;
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApi(configureJwtBearerOptions, configureMicrosoftIdentityOptions) ;
Run Code Online (Sandbox Code Playgroud)

现在,当我从邮递员调用 API 时,它会抛出错误以及状态代码 500:

System.InvalidOperationException:IDX20803:无法从以下位置获取配置:“https://graph.microsoft.com/{tenantId}/v2.0/.well-known/openid-configuration”。---> System.IO.IOException:IDX20807:无法从以下位置检索文档:“https://graph.microsoft.com/{tenantId}/v2.0/.well-known/openid-configuration”。HttpResponseMessage:'状态代码:401,ReasonPhrase:'未经授权',版本:1.1,内容:System.Net.Http.HttpConnectionResponseContent

如何才能妥善解决这一问题呢?

小智 1

超载你AddMicrosoftIdentityWebApi"AzureAd"之后Configuration

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
Run Code Online (Sandbox Code Playgroud)

  • 他询问如果没有可用的 IConfiguration 如何执行此操作。我有同样的问题,我们使用自己的配置格式,需要显式传递这些值。 (5认同)