Luk*_*988 1 c# jwt asp.net-identity asp.net-core identityserver4
我有一个使用 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"
};
});
Run Code Online (Sandbox Code Playgroud)
(正如您所看到的注释代码,我一直在尝试几种设置)
当我解码 JWT(使用 jwt.io)时,我看到 JWT 中有声明“sub”并且有字符串值(dbo 中用户的内部 ID)
{
"nbf": 1592585433,
"exp": 1592585763,
"iss": "https://*************",
"aud": "api_10",
"sub": "142",
"scope": [
"openid",
"api_10"
]
}
Run Code Online (Sandbox Code Playgroud)
问题是 dotnet 将 sub 切换到名称声明。这不返回 (0) 结果:
principal.Claims.Where(w => w.Type == "sub")
这将返回 userId 我需要“142”:
principal.Claims.Where(w => w.Type == ClaimTypes.Name || ClaimTypes.NameIdentifier)
到底是怎么回事?!我的子索赔去哪儿了?
小智 8
只需添加JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();API 的ConfigureServices方法即可。它也在其他评论中提出了建议。我在我的示例 repo上验证了它。
这个问题是因为OIDC StandardClaims在 JWT 令牌处理程序上被重命名。通过添加,JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();您将清除 JWT 令牌处理程序上的入站声明类型映射。
在这里阅读更多
| 归档时间: |
|
| 查看次数: |
1397 次 |
| 最近记录: |