.net core 的claim type声明冲突,nameidentifier与sub

claim type的规范差异:

1、.NET Core的默认Claim Type规范

.NET Core的System.Security.Claims命名空间继承自早期的WS-*协议(如SAML),使用URI格式的Claim Type(如http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier )以确保全局唯一性。这是微软身份框架的历史遗留设计。

2、JWT标准的短名称规范

现代JWT(RFC 7519)采用简洁的短名称(如sub、iss),目的是减少令牌体积并提升可读性。例如:

  • sub → Subject(用户唯一标识)
  • nameidentifier → 对应JWT中的sub

解法:

Services.AddAuthentication()前添加

// 禁用默认声明映射
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.MapInboundClaims = false; // 关闭自动映射
        // ...其他配置...
    });

可参考: https://learn.microsoft.com/zh-cn/aspnet/core/security/authentication/claims?view=aspnetcore-9.0

posted @ 2025-04-10 14:34  Cody&  阅读(58)  评论(0)    收藏  举报