0

I have looked various places on the internet, I have not seen how my signature is different from other implementations:

    string CreateToken(User user)
    {
        var header = new
        {
            typ = "JWT",
            alg = "HS256"
        };
        var claim = new
        {
            iat = ToUnixTime(DateTime.UtcNow),
            jti = Guid.NewGuid(),
            email = user.Email,
            name = user.UserId,
        };

        string headerAndClaim =
            Base64UrlEncode(JsonConvert.SerializeObject(header)) +
            "." +
            Base64UrlEncode(JsonConvert.SerializeObject(claim));

        var key = Encoding.UTF8.GetBytes("MySecret");
        string signature = null;
        using (var signer = new HMACSHA256(key))
        {
            signature = Encoding.UTF8.GetString
                (
                    signer.ComputeHash(Encoding.UTF8.GetBytes(headerAndClaim))
                );

        }

        return
            headerAndClaim +
            "." +
            Base64UrlEncode(signature);
    }

    private static string Base64UrlEncode(string input)
    {
        input = Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
        input = input.Split('=')[0];
        input = input.Replace('+', '-');
        input = input.Replace('/', '_'); 
        return input;
    }

My payload and header checkout fine in the debugging tool https://jwt.io/

But my signiture is always invalid, and just does not look correct.

Where have I gone wrong here?

TheCatWhisperer
  • 901
  • 2
  • 12
  • 28

0 Answers0