javascripttokenrecaptcharecaptcha-v3

reCAPTCHA V3: how to deal with expired token after idle?


For Google reCAPTCHA V2 it was clear what to do when the token gets expired because of idle: the customer has a change to click on the reCaptcha checkbox again. For Google reCAPTCHA V3 it is different as it is unclear when the token gets expired because of idle.

For reCAPTCHA V3 it is suggested by Google:

https://developers.google.com/recaptcha/docs/v3

  1. Load the JavaScript api with your sitekey

  2. Call grecaptcha.execute on an action or when the page loads // we choose when the page loads, OK?

  3. Send the token to your backend with the request to verify // upon button click

OK. If the button was clicked several minutes later than the page was loaded, the V3 token we send to backend is already expired. What's the proper way to deal in this situation? Should we silently auto-update the token by sending calls to Google every minute? What's the best approach for this case? I didn't find any suggestions from Google.


Solution

  • Since reCAPTCHA tokens expire after two minutes, this is how I have put it to work:

    Step 1: Load the captcha token on page load (as usual)

    Step 2: Use a SetInterval function to reload the token every 90 seconds, so that the reCAPTCHA token is refreshed before it expires after 2 minutes.

    // Onload
    grecaptcha.ready(function () {
      grecaptcha.execute('YOUR_KEY_HERE', { action: 'request_call_back' }).then(function (e) {
        $('#YOUR_FIELD_NAME_ID').val(e);
      });
    });
    
    // Every 90 Seconds
    setInterval(function () {
      grecaptcha.ready(function () {
        grecaptcha.execute('YOUR_KEY_HERE', { action: 'request_call_back' }).then(function (e) {
          $('#YOUR_FIELD_NAME_ID').val(e);
        });
      });
    }, 90 * 1000);