Reputation: 5876
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", "[email protected]" },
{ "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.
Upvotes: 3
Views: 8495
Reputation: 27357
You're getting the bytes incorrectly for the key:
var payload = new Dictionary<string, object>()
{
{ "sub", "[email protected]" },
{ "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
.
Upvotes: 6