ASP.NET Core JWT 身份验证更改声明(子)
Posted
技术标签:
【中文标题】ASP.NET Core JWT 身份验证更改声明(子)【英文标题】:ASP.NET Core JWT authentication changes Claims (sub) 【发布时间】:2020-10-09 23:51:04 【问题描述】:我有一个使用 JWT 身份验证的 ASP.NET Core API。简单设置:
....
string authority = $"https://configuration["Auth:Authority"]";
string audience = configuration["Auth:Audience"];
return builder.AddJwtBearer(options =>
options.Authority = authority;
options.Audience = audience;
options.TokenValidationParameters = new TokenValidationParameters
// NameClaimType = "http://schemas.org/email"
// NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email"
// NameClaimType = "sub"
;
);
(你可以看到注释代码,我已经尝试了几个设置)
当我解码 JWT(使用 jwt.io)时,我看到 JWT 中有声明“sub”并且具有字符串值(dbo 中用户的内部 ID)
"nbf": 1592585433,
"exp": 1592585763,
"iss": "https://*************",
"aud": "api_10",
"sub": "142",
"scope": [
"openid",
"api_10"
]
问题是 dotnet 将 sub 切换到名称声明。这不会返回 (0) 个结果:
principal.Claims.Where(w => w.Type == "sub")
这返回 userId 我需要“142”:
principal.Claims.Where(w => w.Type == ClaimTypes.Name || ClaimTypes.NameIdentifier)
这是怎么回事?!我的子声明哪里去了?
【问题讨论】:
你可能需要JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
这一行。更多解释请阅读this article。
【参考方案1】:
只需在 API 的 ConfigureServices
方法上添加 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
。它也对其他评论提出了建议。我在我的sample repo 上验证了它。
这个问题是因为 OIDC StandardClaims 在 JWT 令牌处理程序上被重命名。通过添加 JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
,您将清除 JWT 令牌处理程序上的入站声明类型映射。
阅读更多here
【讨论】:
以上是关于ASP.NET Core JWT 身份验证更改声明(子)的主要内容,如果未能解决你的问题,请参考以下文章
我可以使用我的 JWT 进行身份验证,但我的名称声明在我的 ASP.NET Core 应用程序中无法识别
ASP.Net Core - 使用 WebAPI 和 MVC 前端的 JWT 身份验证不起作用