asp net core下 JWT 部分 密鑰生成錯誤(IDX10720)和 Claim 類型映射問題
概述
探討 JWT 簽發與驗證中的常見問題:密鑰生成錯誤(IDX10720)和 Claim 類型映射問題,提供解決方案與代碼示例,助你輕松避坑。
踩坑詳情
坑一: IDX10720 錯誤 - 無法為算法 'HS256' 創建 KeyedHashAlgorithm
問題描述
在項目中引入了Microsoft.AspNetCore.Authentication.JwtBearer (6.0.26) 由 6.0.25 升級,之前用于簽發 JWT Token 的代碼報錯:IDX10720: Unable to create KeyedHashAlgorithm for algorithm 'HS256'"
問題代碼示例
var credentials=GenerateCredentials(_options.Key);
var header = new JwtHeader(credentials);
var payload = new JwtPayload(_options.Issuer,_options.Audience,claim,notBefore,expoires);
var token = new JwtSecurityToken(header, payload);
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.WriteToken(token);
SigningCredentials GenerateCredentials(string key)
{
return new SigningCredentials(GenerateKey(key), SecurityAlgorithms.HmacSha256);
}
SecurityKey GenerateKey(string key)
{
return new SymmetricSecurityKey(MD5.HashData(Encoding.UTF8.GetBytes(str)));
}
問題原因
Microsoft.AspNetCore.Authentication.JwtBearer(6.0.26) 版本依賴的下游包 Microsoft.IdentityModel.Protocols.OpenIdConnect(6.35.0) 對密鑰的生成方式進行了更嚴格的校驗,要求密鑰必須滿足特定算法的位數要求。
使用 MD5 生成的密鑰長度不符合 HS256 算法的要求。
具體下游包升級詳情
Microsoft.AspNetCore.Authentication.JwtBearer 6.0.25 -> 6.0.26
Microsoft.IdentityModel.Protocols.OpenIdConnect 6.10.0 -> 6.35.0
解決方案
根據項目情況,選擇以下方案之一:
-
降Microsoft.AspNetCore.Authentication.JwtBearer至6.0.25
-
使用SHA256 生成密鑰,滿足位數要求
SHA256.HashData()
相關資料
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/pull/2072
https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer/6.0.25#dependencies-body-tab
https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.JwtBearer/6.0.26#dependencies-body-tab
坑二: JwtRegisteredClaimNames.Sub類型映射問題
問題描述
在簽發 JWT Token 時使用了特定的 Claim 類型(如 JwtRegisteredClaimNames.Sub),但在使用 HttpContext.User.Claims 讀取時無法正確獲取。
問題代碼示例
var claim = new Claim(JwtRegisteredClaimNames.Sub,Id);
// cant find
var claim = Httpcontext.User.Claims.FirstOrDefault(x=>x.Key == JwtRegisteredClaimNames.Sub);
// you shold use like this to find
var claim = Httpcontext.User.Claims.FirstOrDefault(x=>x.Key == ClaimTypes.NameIdentifier);
問題原因
JwtSecurityTokenHandler 默認會將一些標準的 JWT Claim 類型映射到 .NET 的 ClaimTypes。例如,JwtRegisteredClaimNames.Sub 會被映射為 ClaimTypes.NameIdentifier。
解決方案
根據項目情況,選擇以下方案之一:
- 將
MapInboundClaims設置成false
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
handler.MapInboundClaims = false;
//or
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear()
- 使用自定義字段 映射
var claim = new Claim("your_type",Id);
var claim = Httpcontext.User.Claims.FirstOrDefault(x=>x.Key == "your_type");
- 使用
ClaimTypes.NameIdentifier來獲取被Mapping后的值
var claim = Httpcontext.User.Claims.FirstOrDefault(x=>x.Key == ClaimTypes.NameIdentifier);
相關資料
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/415

浙公網安備 33010602011771號