【发布时间】:2021-11-10 18:27:28
【问题描述】:
我有一个 .NET 5 项目。我正在尝试在其中生成 JWT。这一行给我一个部署到 IIS Web 服务器的错误:JwtSecurityTokenHandler().WriteToken(token)
The encryption algorithm 'System.String' requires a key size of at least 'System.Int32' bits.
Key 'Microsoft.IdentityModel.Tokens.SymmetricSecurityKey', is of size: 'System.Int32'. (Parameter 'key')
我在其中添加了注释代码,以测试进入令牌生成的值是否正常,并且密钥长度为 16 个字符(我已经测试了更多但仍然失败)。
这在我的本地环境中运行良好。
有人知道为什么会这样吗?
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_jwtConfig.Value.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_jwtConfig.Value.Issuer,
_jwtConfig.Value.Audience,
claims,
expires: DateTime.UtcNow.AddDays(30),
signingCredentials: creds);
//return new JsonResult(new Dictionary<string, object>
// {
// { "secretkey", _jwtConfig.Value.SecretKey },
// { "creds", creds.ToString() },
// { "issuer", _jwtConfig.Value.Issuer },
// { "audience", _jwtConfig.Value.Audience },
// { "token", token.ToString() }
// });
return new JsonResult(new Dictionary<string, object>
{
{ "access_token", new JwtSecurityTokenHandler().WriteToken(token) },
});
来自Startup.cs的相关部分:
services.Configure<JWTSettings>(Configuration.GetSection("JWTSettings"));
services.AddAuthentication()
.AddCookie()
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.IncludeErrorDetails = true;
var secretKey = Configuration.GetSection("JWTSettings:SecretKey").Value;
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = Configuration.GetSection("JWTSettings:Issuer").Value,
ValidateAudience = true,
ValidAudience = Configuration.GetSection("JWTSettings:Audience").Value,
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
};
})
【问题讨论】:
-
_jwtConfig.Value.SecretKey 的值是多少?似乎价值来自当地环境。启动文件中secretKey的长度是多少?
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)) -
它的长度超过 16 个字符 @BruceZhang 是 HmacSHA256 所必需的,从
appsettings.json文件中提取。当我取消注释注释部分时(我将其放入以便我可以看到它通过了什么),我可以看到它是正确的值。