如何添加 JwtBearer 以及 AddMicrosoftIdentityWebAppAuthentication

Bri*_*hah 5 c# asp.net-core microsoft-identity-platform asp.net-core-3.1

我不确定我是否完全理解 Microsoft.Identity.Web 的更改,但我正在关注一篇文章(由 Microsoft 提供),其中描述了如何在启动时进行更改

 services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
     .AddAzureAD(options => Configuration.Bind("AzureAd", options));
Run Code Online (Sandbox Code Playgroud)

services.AddMicrosoftIdentityWebAppAuthentication(Configuration);
Run Code Online (Sandbox Code Playgroud)

虽然这看起来很好很简单,但我还有更多工作要做,因为我现有的代码中有以下代码片段

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
   .AddAzureAD(options => this.configuration.Bind("AzureAd", options))
   .AddJwtBearer(options =>
   {
       //this code used to validate signing keys
       string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
       IConfigurationManager<OpenIdConnectConfiguration> configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
       OpenIdConnectConfiguration openIdConfig = configurationManager.GetConfigurationAsync(CancellationToken.None).GetAwaiter().GetResult();
       var tenantId = this.configuration["TenantId"];
       var validIssuer = $"https://sts.windows.net/{tenantId}/";

       options.TokenValidationParameters = new TokenValidationParameters()
       {
           ValidIssuer = validIssuer,
           ValidAudience = this.configuration["ClientId"],
           IssuerSigningKeys = openIdConfig.SigningKeys,
       };
  });
Run Code Online (Sandbox Code Playgroud)

为了给您提供一些背景信息,我们对该应用程序有两种变体

  1. 用户登录并执行一些操作(此处用户将看到 Microsoft 登录对话框以使用他/她的凭据登录)
  2. Microsoft Azure 使用一些令牌调用我们的端点,我们需要验证该令牌。

您在上面看到的 JWTvaliation 部分适用于第二项,一旦我们收到令牌,我们就会在无需登录和 UI 工作流程的情况下验证该令牌。

问题: 上面的代码运行正常。这里唯一的问题是,如果我们喜欢使用,Microsoft.Identity我们应该如何使用第二项(JWT),因为services.AddAuthentication().AddAzureAD返回IAuthenticationBuilder我们进一步使用它来添加AddJwtBearer,而services.AddMicrosoftIdentityWebAppAuthentication不会返回IAuthenticationBuilder

pok*_*oke 4

AddMicrosoftIdentityWebAppAuthentication实际上只是执行以下操作的一种奇特方式:

\n
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApp(\xe2\x80\xa6)\n
Run Code Online (Sandbox Code Playgroud)\n

因此,它将默认方案配置为 OIDC 方案,并运行AddMicrosoftIdentityWebApp以配置最终执行的操作。

\n

现在,AddAuthentication实际上可以对服务集合进行多次调用。您只需要小心不要错误地重新配置即可。无参数函数不会这样做,因此这是访问IAuthenticationBuilder以进一步配置身份验证的好方法。

\n

这意味着您可以像这样更改代码:

\n
// configure Microsoft Identity Web first\n// this also sets the default authentication to OIDC\nservices.AddMicrosoftIdentityWebAppAuthentication(Configuration);\n\n// retrieve an authentication builder without changing the default\nservices.AddAuthentication()\n    // add JWT bearer now\n   .AddJwtBearer(options =>\n   {\n       // \xe2\x80\xa6\n   });\n
Run Code Online (Sandbox Code Playgroud)\n