Search code examples
asp.net-mvcfirebaserecaptcha-v3

CAPTCHA_CHECK_FAILED : Recaptcha verification failed - SITE_MISMATCH


I am trying to implement Verify phone number functionality in one of my ASP.NET MVC projects.

Added below to code send verification code on user's mobile number, After successfully generating and verifying google recaptcha.

using (var httpClient = new HttpClient())
{
      var data = new { phoneNumber, recaptchaToken };
      var content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
      var url = $"https://www.googleapis.com/identitytoolkit/v3/relyingparty/sendVerificationCode?key={_configuration["Firebase:WebApiKey]}"";
      var response = await httpClient.PostAsync(url, content);
      var responseContent = await response.Content.ReadAsStringAsync();

      response.EnsureSuccessStatusCode();

      return JsonConvert.DeserializeObject<VerificationResponse>(responseContent) ?? throw new InvalidOperationException();
}

I'm getting this error response from sendVerificationCode API request and not receiving SMS OTP on user's mobile number:

{
"error": {
"code": 400,
"message": "CAPTCHA_CHECK_FAILED : Recaptcha verification failed - SITE_MISMATCH",
"errors": [
 {
"message": "CAPTCHA_CHECK_FAILED : Recaptcha verification failed - SITE_MISMATCH",
"domain": "global",
"reason": "invalid"
  }
 ]
}
}

Web API key, Site key and Site secret copied from Firebase are configured properly in my ASP.NET MVC code.

Not sure what is the root cause of this error. I am using recaptcha Version3.

Can someone please help?


Solution

  • As per the Google Cloud documentation sendVerificationCode Endpoints expect and work for the recatcha token generated using getRecaptchaParams web API endpoint, it does not work with a recaptcha token generated through any other ways.

    Below are the steps I followed to resolve above issue.

    1. I created an Action method that returns recaptch params.

      public async Task<ActionResult> GetRecaptchaTokenParam()
      {
       using (var httpClient = new HttpClient())
       {
        var apiKey = "Paste your API Key Here";
        var url = $"https://identitytoolkit.googleapis.com/v1/recaptchaParams?key={apiKey}";
        var response =await httpClient.GetAsync(url);
        var responseContent = await response.Content.ReadAsStringAsync();
        response.EnsureSuccessStatusCode();
        var str = JsonConvert.DeserializeObject<TestModel>(responseContent);
        return Json(str, JsonRequestBehavior.AllowGet);
        }
       }
      
    2. Add the Below HTML tag on your HTML page

       <div id="recaptcha-container"></div>
      
    3. This is the javascript code to Get the recaptcha token params and Generate the token once user check the recaptcha checkbox. once the recaptcha token is generated by below code, pass it to sendVerification Api end point with mobile number.

        function GetRecaptchaToken() {
        return fetch(../MFA/GetRecapatchaParams, {
        method: 'GET'
         })
        .then(response => response.json())
        .then(data => {
        console.log(data.recaptchaSiteKey);
        return data.RecaptchaSiteKey;
       });
      }
      
        GetRecaptchaToken().then(recaptchaSiteKey => {
        grecaptcha.render('recaptcha-container', {
        'sitekey': recaptchaSiteKey,
        'callback': function (response) {
        var recaptchaToken = response;
        // Pass this recaptchaToken parameter to sendVerificationCode API
      
        },
       'expired-callback': function () {
        console.log('Recaptcha response expired.');
        $('.div-recaptcha-container').show();
        $('.div-verification-form-fields').hide();
        }
       });
       });