简体   繁体   中英

JWT token generated with jose-jwt and jwt.io

I'm trying to generate JWT token in .NET. 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". 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/ ". Indeed, I copy/paste the generated token, I enter "myawesomekey" as the key but it keeps telling me "invalid signature".

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. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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