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

问题描述 投票:0回答:2

我正在使用

Microsoft.Identity.Web
库来验证 .Net Core Web API 中的令牌。

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

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

        ------------
}

但根据文档here,我需要通过 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) ;

现在,当我从邮递员调用 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

如何正确解决这个问题?

c# asp.net-core asp.net-identity access-token microsoft-identity-platform
2个回答
4
投票

适用于.net 6

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

2
投票

AddMicrosoftIdentityWebApi
 之后使用 
"AzureAd"
 使您的 
Configuration

超载
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
© www.soinside.com 2019 - 2024. All rights reserved.