在令牌生成方法中使用EncryptingCredentials时发生JWT加密错误

时间:2020-05-29 07:30:56

标签: asp.net-core jwt

我在 ASP.net核心3.1 Web API中实现了 JWT令牌。 在尝试使用 EncryptingCredentials 的令牌生成方法中,出现以下错误:

IDX10662:KeyWrap算法'System.String'要求密钥大小为'System.Int32'位。键''的大小为:'System.Int32'。 (参数“长度”)

这是我的令牌生成方法:

public async Task<string> GenerateAsync(User user)
    {
        var secretKey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.SecretKey); //"SampleSecretKeyChange" 
        var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature);

        var encryptionkey = Encoding.UTF8.GetBytes(_siteSetting.JwtSettings.Encryptkey);  //"AbcdefgHijklmnopk123456"
        var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(encryptionkey), SecurityAlgorithms.Aes128KW, SecurityAlgorithms.Aes128CbcHmacSha256);

        var descriptor = new SecurityTokenDescriptor
        {
            Issuer = _siteSetting.JwtSettings.Issuer,
            Audience = _siteSetting.JwtSettings.Audience,
            IssuedAt = DateTime.Now,
            NotBefore = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.NotBeforeMinutes),
            Expires = DateTime.Now.AddMinutes(_siteSetting.JwtSettings.ExpirationMinutes),
            SigningCredentials = signingCredentials,
            EncryptingCredentials = encryptingCredentials,
            Subject = new ClaimsIdentity(_getClaims(user))
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var securityToken = tokenHandler.CreateToken(descriptor);
        var jwt = tokenHandler.WriteToken(securityToken);           
        return await Task.FromResult(jwt);
    }

1 个答案:

答案 0 :(得分:0)

在进行了所有研究之后,我发现了问题所在。如果要在我描述的 Encryptkey 密钥长度条件下使用 EncryptingCredentials ,必须等于 16 个字符。