【问题标题】:JwtSecurityToken understanding and exceptionJwtSecurityToken 理解与异常
【发布时间】:2019-03-06 09:27:12
【问题描述】:

我对@9​​87654321@ 还很陌生,我试图了解它的不同方面,以及整个claimsidentityclaimprincipal,但那是另一回事了。

我尝试使用以下代码在 C# 中生成令牌:

private const string SECRET_KEY = "abcdef";
private static readonly SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));

    public static string GenerateToken(string someName)
    {
        var token = new JwtSecurityToken(
            claims: new Claim[]
            {
                new Claim(ClaimTypes.Name, someName), 
            },
            notBefore: new DateTimeOffset(DateTime.Now).DateTime,
            expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime,
            signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256)
        );

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

我遵循了 Youtube 上的教程,但我不确定我是否理解 JwtSecurityToken 中的不同部分。另外,当我执行 通过控制器的代码只是为了尝试返回一个令牌,它 返回一个错误,说:“IDX10603:解密失败。密钥尝试: '[PII 被隐藏]'"。

感谢任何帮助。

【问题讨论】:

    标签: asp.net .net asp.net-core jwt


    【解决方案1】:

    您应该为您的密钥添加足够的字符。当你在这里设置你的密钥时,

    //your SECRET_KEY = "abcdef"
    new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
    

    改成

    new SymmetricSecurityKey(Encoding.UTF8.GetBytes("somethingyouwantwhichissecurewillworkk"));
    

    这应该可以。

    【讨论】:

      【解决方案2】:

      算法 HS256 要求 SecurityKey.KeySize 大于 128 位,而您的密钥只有 48 位。通过添加至少 10 个以上的符号来扩展它。 至于“PII 被隐藏”部分,它是作为 GDPR 合规性工作的一部分,以隐藏日志中的任何堆栈或变量信息。您应该启用其他详细信息:

      IdentityModelEventSource.ShowPII = true;
      

      【讨论】:

        猜你喜欢
        • 2013-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多