1
votes

i am trying to generate a valid JWT Token with C#, My code is

        string secret = "6ASu2c8V/zF..........******"; // base64encoded
        var payload = new Dictionary<string, string>
        {
            {"iss", "http://webapi.one*******"},
            {"exp", "1498140965"},
            {"aud", "ONE****"},
            {"playauth", "Ygo2s********"}
        };

        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        var token = encoder.Encode(payload,secret);
        return token;

When i run the code it generated token

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vd2ViYXBpLm9uZXJlZWwubmV0IiwiZXhwIjoxNDk4MTQwOTY1LCJhdWQiOiJPTkVSRUVMIiwicGxheWF1dGgiOiJZZ28yc2Nob29sQG5pdGU5JCJ9.MuWc9tebE8IZFOIFsh2E_JP-UFQl4UZ9kTBG19_REnM

but this token shows invalid signature on https://jwt.io/ and i used the correct secret key on Verify Signature

1
You have (almost) the same code as in my question. Double and triple check that you're copying everything into jwt.io correctly. Make a new (temporary) secret key, and add it to the question along with the token so we can verify. - user47589
One difference I see is that my secret key is just a long hex string (e.g. 28f029d79bedb87....), whereas yours is (apparently) base64 encoded. - user47589

1 Answers

2
votes

I finally solved it. i converted my based64 encoded token to bytes array and it worked perfectly. Here,s the new code:

        byte[] secret = Convert.FromBase64String("6ASu2c8V/zF*******");

        var payload = new Dictionary<string, object>
        {
            {"iss", "http****"},
            {"aud", "O***"},
            {"exp", expiryDate},
            {"nbf", createdDate}
        };

        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

        var token = encoder.Encode(payload, secret);
        return token;