我试图在.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;
}
当我尝试使用网站&#34; https://jwt.io/&#34;测试生成的令牌时,我遇到了问题。实际上,我复制/粘贴生成的令牌,我输入&#34; myawesomekey&#34;作为关键,但它一直告诉我&#34;无效签名&#34;。
我可以忽略它(因为我的C#代码中的解码工作),但我很好奇,我想知道如何通过网站解码失败。我唯一的想法是,在C#代码中,我必须将密钥作为字节数组传递,所以也许只是传递&#34; myawesomekey&#34;到网站。
答案 0 :(得分:4)
您获取密钥的字节错误:
{
"close_on_stop": true,
"pretty_output": true,
"launch_browser": true,
"debug": true,
"ide_key": "sublime.xdebug",
"port": 9001,
}
工作正常。这可能是 导致var payload = new Dictionary<string, object>()
{
{ "sub", "mr.x@contoso.com" },
{ "exp", 1300819380 }
};
var secretKey = Encoding.UTF8.GetBytes("myawesomekey");
string token = JWT.Encode(payload, secretKey, JwsAlgorithm.HS256);
return token;
问题的原因。