我正在将旧版 .NET 应用程序迁移到 .NET 8,其中身份验证从本地身份数据库移至 Azure AD B2C。在这里,我首先检查Azure AD B2C。如果用户不可用,我会签入本地数据库,然后将用户从本地数据库迁移到 Azure AD B2C。
为了实现 Azure AD B2C 身份验证,我在 Program 类中配置了身份验证。
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAdB2C", options);
},
options => { Configuration.Bind("AzureAdB2C", options); });
此外,我使用内置的身份提供程序和 UserManager 对本地身份数据库进行身份验证。
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetValue<string>("ConnectionStrings:DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
我使用 SignUpSignIn 用户流对 Azure AD B2C 用户进行身份验证。在我的 AuthController.cs API 中,登录端点处理用户身份验证。
[HttpPost("login")]
[AllowAnonymous]
public async Task<IActionResult> Login(UserCredentials model)
{
if (ModelState.IsValid)
{
var user = _userManager.Users.FirstOrDefault(x => x.Email == model.Email);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
return Ok();
}
}
return Unauthorized();
}
使用 Azure AD B2C 成功进行身份验证后,访问受保护资源的后续请求失败,并出现以下异常。
HttpRequestException: Invalid status code in the HttpResponseMessage: NotFound.
TodoListClient.Services.TodoListService.GetAsync() in TodoListService.cs
throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}.");
TodoListClient.Controllers.TodoListController.Index() in TodoListController.cs
当用户通过 Azure AD B2C 成功登录时,后续请求会出现此异常。
我遵循了 Microsoft 中的文档在示例 Web 应用程序中配置身份验证,我所做的唯一额外配置是将身份服务添加到 Web API。但是,当在程序中同时配置 Azure AD B2C 身份验证和身份身份验证服务时,我遇到了问题。是否有特定的方法可以将这些服务一起配置,或者同时使用它们是否有限制?
出现此问题的原因是,同时启用这两种配置可能会导致对 API 请求使用哪种身份验证方法产生混淆。
处理这种情况的一种更简单的方法是选择单个身份验证提供程序。就我而言,我保留 Azure AD B2C 来处理所有身份验证要求并删除了 services.AddIdentity 配置。此外,我创建了一个单独的项目来处理身份数据库 (
AddIdentity
)。
建议: 如果有人遇到此问题并且两个提供商都是必需的,请实施一种机制来根据特定标准(例如请求来源、用户类型)选择适当的提供商。但是,这需要更复杂的设置并仔细处理整个应用程序中的身份验证逻辑,这可能会产生不必要的开销。