【发布时间】:2017-10-02 01:23:52
【问题描述】:
我正在尝试在 .NET 中生成 JWT 令牌。起初,我尝试使用“System.IdentityModel.Tokens.Jwt”,但在验证令牌期间出现问题,因此我切换到“jose-jwt”。即使我可以使用这段代码创建和验证令牌:
private byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public string Login(LoginInformation credential)
{
var payload = new Dictionary<string, object>()
{
{ "sub", "mr.x@contoso.com" },
{ "exp", 1300819380 }
};
var secretKey = GetBytes("myawesomekey");
string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
string json = JWT.Decode(token, secretKey);
return json;
}
当我尝试使用站点“https://jwt.io/”测试生成的令牌时遇到问题。实际上,我复制/粘贴生成的令牌,输入“myawesomekey”作为密钥,但它一直告诉我“签名无效”。
我可以忽略这一点(因为我的 C# 代码中的解码有效),但我很好奇,我想知道如何通过站点进行解码失败。我唯一的想法是,在 C# 代码中,我必须将密钥作为字节数组传递,因此仅将“myawesomekey”传递给站点可能是无效的。
【问题讨论】: