简体   繁体   English

用jose-jwt和jwt.io生成的JWT令牌

[英]JWT token generated with jose-jwt and jwt.io

I'm trying to generate JWT token in .NET. 我正在尝试在.NET中生成JWT令牌。 At first, I tried to use "System.IdentityModel.Tokens.Jwt" but it was causing an issue during the validation of the token, so I switched to "jose-jwt". 最初,我尝试使用“ System.IdentityModel.Tokens.Jwt”,但是这在令牌验证期间引起了问题,因此我切换到“ jose-jwt”。 Even though I can create and validate a token with this piece of code: 即使我可以使用以下代码创建并验证令牌:

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;

}

I have an issue when I try to test the generated token with the site " https://jwt.io/ ". 当我尝试用网站“ https://jwt.io/ ”测试生成的令牌时,我遇到了一个问题。 Indeed, I copy/paste the generated token, I enter "myawesomekey" as the key but it keeps telling me "invalid signature". 确实,我复制/粘贴了生成的令牌,我输入“ myawesomekey”作为密钥,但是它一直告诉我“无效签名”。

I could just ignore that (as the decoding in my C# code works), but I'm quite curious and I'd like to know how come the decoding via the site fails. 我只是忽略了这一点(因为C#代码中的解码有效),但是我很好奇,我想知道通过站点解码失败的原因。 The only idea I have is that, in the C# code, I have to pass the key as a byte array, so maybe it's not valid to just pass "myawesomekey" to the site. 我唯一的想法是,在C#代码中,我必须将密钥作为字节数组传递,因此仅将“ myawesomekey”传递给站点也许无效。

You're getting the bytes incorrectly for the key: 您为密钥错误地获取了字节:

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;

Works fine. 工作正常。 This is probably also the cause of your problem with System.IdentityModel.Tokens.Jwt . 这可能也是造成System.IdentityModel.Tokens.Jwt问题的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM