JwtSecurityTokenHandler(). writetoken (token)在托管环境中抛出错误



我有一个。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')

有注释的代码,我放在那里测试进入令牌生成的值是OK的,键是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,
};
})

你似乎有错误IDX10653。

但是你的异常消息没有显示真实的信息。详情请参阅本文。你可以添加代码IdentityModelEventSource.ShowPII = true;并提供真实的异常信息吗?

我想你会看到真正的异常消息,你可以理解发生了什么。极有可能您的SecretKey小于128位。在这种情况下,只需尝试在配置文件中为参数JWTSettings:SecretKey使用更长的值。这里也描述了类似的场景。

这似乎不是编码问题,更多的是关于web主机的。net配置。将应用程序部署为"依赖于框架的";导致错误,但是"Self Contained"代码本身可以工作。

好的,我可能有解决方案,但我不太确定所以请告诉我这是否有效:

我直接在Startup.cs中配置了JWT令牌,如下所示:

Startup.cs

public static void AddIdentityServices(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<JwtSettings>(configuration.GetSection("JwtSettings"));
// Identity stuff
services.AddTransient<IAuthenticationService, AuthenticationService>();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
})
.AddJwtBearer("JwtBearer", o =>
{
o.RequireHttpsMetadata = false;
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidIssuer = configuration["JwtSettings:Issuer"],
ValidAudience = configuration["JwtSettings:Audience"],
ClockSkew = TimeSpan.FromMinutes(5),
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(configuration["JwtSettings:Key"]))
};
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 500;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync($"{c.Exception.ToString()} JwtBearerEvents in IdentityServiceRegistration");
},
OnChallenge = context =>
{
context.HandleResponse();
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject("401 Not authorized");
return context.Response.WriteAsync(result);
},
OnForbidden = context =>
{
context.Response.StatusCode = 403;
context.Response.ContentType = "application/json";
var result = JsonConvert.SerializeObject("403 Not authorized");
return context.Response.WriteAsync(result);
},
};
});
}

这是我的令牌生成方法使用的CreateUserAsync和其他方法:

private async Task<JwtSecurityToken> GenerateToken(ApplicationUser user)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(JwtRegisteredClaimNames.Nbf,
new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()),
new Claim(JwtRegisteredClaimNames.Exp,
new DateTimeOffset(DateTime.Now.AddYears(10))
.ToUnixTimeSeconds().ToString())
}
.Union(userClaims);
var jwtSecurityToken = new JwtSecurityToken(
new JwtHeader(
new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes("//secret key of 64 characters of capital letters and numbers")),
SecurityAlgorithms.HmacSha256)),
new JwtPayload(claims));
return jwtSecurityToken;
}

你应该能够从这样的网站生成一个密钥:SHA256生成器

如果有帮助请告诉我。

相关内容

  • 没有找到相关文章

最新更新