You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AddMicrosoftIdentityWebApiAuthentication方法失效:Azure B2C验证.NET7 API异常

问题:Azure B2C + .NET 7 API 切换到Microsoft.Identity.Web后身份验证失效

我在给.NET 7 API配置Azure B2C身份验证时,将旧的过时代码:

services.AddAuthentication(AzureADB2CDefaults.JwtBearerAuthenticationScheme)
    .AddAzureADB2CBearer(options => configuration.Bind("AzureAdB2CAuthentication", options));

替换为Microsoft.Identity.Web库的新代码:

services.AddMicrosoftIdentityWebApiAuthentication(configuration,
    "AzureAdB2CAuthentication");

之后身份验证流程完全失效,且我未对Azure B2C实例做任何配置修改。当前appsettings.json中的配置如下:

"AzureAdB2CAuthentication": 
{ 
 "Instance": "<instanceUrl>", 
 "Domain": "<domain>", 
 "TenantId": "<tenantId>", 
 "ClientId": "<clientId>", 
 "SignedOutCallbackPath": "<path>", 
 "SignUpSignInPolicyId": "<policyId>" 
}

排查修复方案

1. 修正配置键映射

Microsoft.Identity.Web与旧AzureADB2C库的配置键命名规则不同:旧库用SignUpSignInPolicyId指定B2C策略ID,新库默认读取Policy键。直接修改appsettings.json中的配置项名称:

"AzureAdB2CAuthentication": 
{ 
 "Instance": "<instanceUrl>", 
 "Domain": "<domain>", 
 "TenantId": "<tenantId>", 
 "ClientId": "<clientId>", 
 "SignedOutCallbackPath": "<path>", 
 "Policy": "<policyId>" 
}

2. 手动指定策略(无需修改配置文件)

如果不想改动配置文件,可以在代码中手动构造Authority并指定策略:

services.AddMicrosoftIdentityWebApiAuthentication(configuration, "AzureAdB2CAuthentication");

// 手动配置JwtBearer选项,指定B2C策略
services.Configure<JwtBearerOptions>(Microsoft.Identity.Web.Constants.Bearer, options =>
{
    var config = configuration.GetSection("AzureAdB2CAuthentication");
    options.Authority = $"{config["Instance"]}{config["Domain"]}/{config["SignUpSignInPolicyId"]}/v2.0/";
});

3. 验证受众(Audience)设置

默认情况下,Microsoft.Identity.Web会将ClientId作为令牌的受众(Audience)进行验证。如果你的B2C令牌中受众不是API的ClientId,需要在配置中添加Audience字段明确指定:

"AzureAdB2CAuthentication": 
{ 
 // 其他配置项...
 "Audience": "<your-api-audience>" 
}

4. 检查Instance格式

确保Instance的格式为https://<your-tenant-name>.b2clogin.com/(末尾带斜杠),错误的格式会导致Authority构造失败,进而无法正确验证令牌。


内容的提问来源于stack exchange,提问作者Lucas Ferla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:52:34