JWT承载“ IDX10609:解密失败。未尝试任何密钥”

时间:2019-07-07 15:42:27

标签: .net encryption .net-core jwt

我正在尝试解密加密的JWT承载令牌。我的生成代码如下:

private string GenerateToken(IEnumerable<Claim> claims)
{
    var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetValue<string>("JWTServerKey")));
    var secret = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetValue<string>("JWTServerSecret")));

    var signingCreds = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
    var encryptingCreds = new EncryptingCredentials(secret, SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);
    var handler = new JwtSecurityTokenHandler();

    var token = handler.CreateJwtSecurityToken(
        "test",
        "test",
        new ClaimsIdentity(claims),
        DateTime.Now,
        DateTime.Now.AddMinutes(20),
        DateTime.Now,
        signingCreds,
        encryptingCreds);

    return new JwtSecurityTokenHandler().WriteToken(token);
}

在startup.cs上,我的代码如下:

options.TokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    ValidIssuer = "test",
    ValidAudience = "test",
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTServerKey"])),
    TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTServerSecret"]))
};

我遇到以下异常:“ IDX10609:解密失败。未尝试任何密钥”。 我究竟做错了什么??



编辑:

我的示例未包含实际密钥,但是它的长度为128位。

1 个答案:

答案 0 :(得分:0)

根本原因::密钥太短,您必须将JWTServerSecret更改为更长的其他名称(即JWTServerSecret2)。

对于SecurityAlgorithms.Aes128KWSecurityAlgorithms.Aes128CbcHmacSha256,秘密长度必须为128位。

将以下行添加到ConfigureServices(IServiceCollection services)中的Startup.cs,以显示更多详细信息日志。

IdentityModelEventSource.ShowPII = true;
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ValidIssuer = "test",
        ValidAudience = "test",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTServerKey"])),
        TokenDecryptionKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWTServerSecret"]))
    };
});