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

ASP.NET Core 8升级后OpenID Connect的sub Claim缺失问题求助

解决ASP.NET Core 8.0中OpenID Connect sub声明被映射的问题

问题原因

ASP.NET Core 8.0对OpenID Connect(OIDC)中间件的声明映射逻辑做了调整:OIDC中间件现在拥有独立的声明映射配置,不再完全依赖JwtSecurityTokenHandler.DefaultInboundClaimTypeMap的全局设置。即使你清除了JWT的默认映射,OIDC中间件仍会默认将标准OIDC声明(如sub)映射到WS-Federation格式的声明类型(http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier),导致原代码无法找到sub声明。

解决方案

在配置OIDC中间件时,直接清除或修改它自身的ClaimTypeMap即可:

方案1:清除所有OIDC默认声明映射

如果希望保留所有原始OIDC声明的名称,直接清除OIDC中间件的默认映射:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    // 你的基础OIDC配置(Authority、ClientId等)
    options.Authority = "https://your-identity-provider.com";
    options.ClientId = "your-client-id";
    options.ClientSecret = "your-client-secret";
    options.ResponseType = "code";

    // 关键:清除OIDC中间件的默认声明映射
    options.ClaimTypeMap.Clear();

    // 保留原有的JWT全局映射清除(可选,若需全局禁用JWT声明映射)
    System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
});

方案2:仅移除sub的映射

如果需要保留其他OIDC声明的默认映射,只移除sub的映射规则:

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    // 你的基础OIDC配置
    options.Authority = "https://your-identity-provider.com";
    options.ClientId = "your-client-id";
    options.ClientSecret = "your-client-secret";
    options.ResponseType = "code";

    // 仅移除sub的默认映射
    options.ClaimTypeMap.Remove("sub");
});

验证

配置完成后,重新运行项目,执行User.Identity.FindFirst("sub")即可获取到原始的sub声明,不会再触发NullReferenceException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:21:06