Auth0 Home Blog Docs

getting exception :Invalid JWT Signature ?

jwt
invalid-signature
jwt-validation
jwtconfiguration

#1

Hello
I am attaching my code here,Please let me know the best solution if any one knows.
Thanks ,in advance…
///
/// This function I am calling to generate access token by passing input JWT
///
public void Login()
{

         //in this function I am using two more function
         //1.ConvertToUnixTimestamp : to calculate time exp,iat value 
         //2.hashing:To generate signature
         try
         {

             string header = @"{'alg':'RS256','typ':'JWT'}";
             var jsonheader = JObject.Parse(header);
             byte] encodedheader = Encoding.UTF8.GetBytes(jsonheader.ToString());
             string encodedheader1 = Encoding.UTF8.GetString(encodedheader);
             string jsonheaderBase64 = Base64UrlEncoder.Encode(encodedheader1);               
             double dtspan = ConvertToUnixTimestamp(DateTime.UtcNow);
             double dtspanExp = dtspan + 3600.0;

             string claims = @"{
                    'iss':'patientbond25-274@aha-careplan-api.iam.gserviceaccount.com',
                    'sub':'patientbond007@gmail.com',
                    'scope':'https://www.googleapis.com/auth/calendar',
                    'aud':'https://www.googleapis.com/oauth2/v4/token', 
                     'exp':'" + dtspanExp + "','iat':'" + dtspan + "'}";

             var jsonclaims = JObject.Parse(claims);

             byte] encodedclaims = Encoding.UTF8.GetBytes(jsonclaims.ToString());
             string encodedclaims1 = Encoding.UTF8.GetString(encodedclaims);
             string jsonclaimsBase64 = Base64UrlEncoder.Encode(encodedclaims1);
       
             var secureInputValue = String.Format("{0}.{1}", jsonheaderBase64, jsonclaimsBase64);

             //In working code i am using the private key value here
             string key = @"-----BEGIN RSA PRIVATE KEY-----KeyValue(not placed just for security)-----END RSA PRIVATE KEY-----";               
             string signature = hashing(secureInputValue,key);
             string signatureBase64 = Base64UrlEncoder.Encode(signature);
             string jwt = String.Format("{0}.{1}.{2}", jsonheaderBase64, jsonclaimsBase64, signatureBase64);
         
             var request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/oauth2/v4/token");
                 request.Method = "Post";
                 request.ContentType = "application/x-www-form-urlencoded";

             string grant_type = "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer";//Encode("urn:ietf:params:oauth:grant-type:jwt-bearer");
             using (var streamWriter = new StreamWriter(request.GetRequestStream()))
             {

                 string json = "grant_type=" + grant_type + "&assertion=" + jwt;
                 streamWriter.Write(json);
                 streamWriter.Flush();
             }

             //while executing the  request I am getting this exception{"error": "invalid_grant", "error_description": "Invalid JWT Signature."}
             var response = (HttpWebResponse)request.GetResponse();
          
             var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

         }
         catch (WebException e)
         {

             using (WebResponse response = e.Response)
             {
                 HttpWebResponse httpResponse = (HttpWebResponse)response;
                 Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                 using (Stream data = response.GetResponseStream())
                 using (var reader = new StreamReader(data))
                 {
                     string text = reader.ReadToEnd();
                     Console.WriteLine(text);
                 }
             }
         }

         return;
     }

     public string hashing(string HeadClaims, string key)
     {

         byte] hashBytes = Encoding.ASCII.GetBytes(HeadClaims);
         StringReader strReader = new StringReader(key);

         PemReader pemReader = new PemReader(strReader);
         AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
         RsaKeyParameters privateKey = (RsaKeyParameters)keyPair.Private;


         ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");

         sig.Init(true, privateKey);
         sig.BlockUpdate(hashBytes, 0, hashBytes.Length);
         byte] signedBytes = sig.GenerateSignature();

         var signedStr = Convert.ToBase64String(signedBytes);
         return signedStr;
        
     }
     public static double ConvertToUnixTimestamp(DateTime date)
     {
         DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
         TimeSpan diff = date.ToUniversalTime() - origin;
         return Math.Floor(diff.TotalSeconds);
     }

#2