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

如何在Web API中验证Azure B2C签发的JWT令牌?

Azure B2C API令牌验证报错修复方案

报错根因

  • No authenticationScheme错误:调用AddAuthentication()时未指定默认JWT认证方案,中间件无法匹配令牌验证逻辑
  • IDX20803错误:Azure B2C要求Authority地址必须追加用户流(策略)后缀,你当前配置的Authority仅为租户根地址,服务无法获取对应OIDC元数据配置导致报错

修复步骤

1. 调整appsettings.json配置

在AzureAdB2C节点补充用户流配置,并修改Authority为带用户流的完整地址:

{
  "AzureAdB2C": {
    "Authority": "https://login.mydomain.net/00000000-0000-0000-0000-000000000000/B2C_1_signupsignin/v2.0/",
    "Audience": "11111111-1111-1111-1111-111111111111",
    "Instance": "https://login.mydomain.net",
    "Domain": "mydomain.net",
    "ClientId": "11111111-1111-1111-1111-111111111111",
    "TenantId": "00000000-0000-0000-0000-000000000000",
    "SignUpSignInPolicyId": "B2C_1_signupsignin"
  },
  // 其余配置保持不变
}

注意将B2C_1_signupsignin替换为你实际在Azure B2C中创建的登录注册用户流名称。

2. 修改认证服务注册逻辑

以下两种方案二选一即可:

方案1:使用Microsoft.Identity.Web封装(推荐)

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

方案2:使用原生JwtBearer配置

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.Audience = Configuration["AzureAdB2C:Audience"];
    options.Authority = Configuration["AzureAdB2C:Authority"];
    // 调试阶段如果有HTTPS证书问题可临时开启,生产环境必须删除
    // options.RequireHttpsMetadata = false;
});

3. 检查中间件注册顺序

中间件必须严格按如下顺序注册,顺序错误也会触发认证异常:

app.UseRouting();

// 认证中间件必须在授权中间件之前
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

有效性校验

配置完成后可直接在浏览器访问{你的Authority地址}.well-known/openid-configuration,能正常返回JSON格式的元数据即说明地址配置正确,返回404则需检查用户流名称、租户ID是否正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:36:02