首页 > 解决方案 > Azure AD B2C 在使用 dotnet core 5.0 构建的后端 Web API 中进行身份验证

问题描述

我尝试在 dotnet 5.0 微服务 webapi 中对 Azure AD B2C 应用程序进行身份验证失败。

我参考了参考托管项目的教程:https ://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2.git

在 Startup.cs 文件的 ConfigureServices 下,我根据示例项目尝试了以下操作:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApi(
                 options =>    {
                      Configuration.Bind("AzureAdB2C", options);
                      options.TokenValidationParameters.NameClaimType = "name";
                  },
                  options => { Configuration.Bind("AzureAdB2C", options);}
           );

我收到以下错误消息:

Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Error: Exception occurred while processing message.

System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'https://xxxxxx.b2clogin.com/Tenant-xxx-xxx-xxx-xxxxxxID/v2.0/.well-known/openid-configuration'
---> System.IO.IOException: IDX20807: Unable to retrieve document from: 'https://xxxxxx.b2clogin.com/Tenant-xxx-xxx-xxx-xxxxxxID/v2.0/.well-known/openid-configuration'. HttpResponseMessage: 'StatusCode: 404, ReasonPhrase: 'Not Found', ...

我还尝试了以下方法:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C"));

上述验证方法返回登录模板 html 页面。

参考 appsettings.json 中不包含 TenantId 的项目,我收到错误消息,抱怨缺少 TenantId。所以现在在 appsettings.json 中,我有以下详细信息:

"AzureAdB2C": {
    "Instance": "https://xxxxxx.b2clogin.com/",
    "ClientId": "xxxx-xxx-xxx-xx-xxxx",
    "Domain": "xxxxxx.onmicrosoft.com/",
    "SigninPolicyId":"B2C_1_testsusi",
    "TenantId": "Tenant-xxx-xxx-xxx-xxxxxxID"
  }

任何帮助是极大的赞赏!

标签: azure.net-coreoauth-2.0azure-ad-b2c

解决方案


由于 appsettings.json 中的键名不正确,该 openId 元数据 URL 中缺少 PolicyId。

将密钥更改为SigninPolicyIdappsettings.jsonSignUpSignInPolicyId中的。

https://docs.microsoft.com/en-us/azure/active-directory-b2c/enable-authentication-web-application?tabs=visual-studio#add-the-app-settings


推荐阅读