reactjsnext.jsrecaptcha-v3react-google-recaptcha

How to verify the token and get score using react-google-recaptcha-v3?


I'm using the library react-google-recaptcha-v3 in order to integrate reCAPTCHA v3 into my React application, which also uses Next.

There's the following example in the README introducing users to the useGoogleReCaptcha hook:

import {
  GoogleReCaptchaProvider,
  useGoogleReCaptcha
} from 'react-google-recaptcha-v3';

const YourReCaptchaComponent  = () => {
  const { executeRecaptcha } = useGoogleReCaptcha();
  const token = executeRecaptcha("login_page");

  return (...)
}

ReactDom.render(
  <GoogleReCaptchaProvider reCaptchaKey="[Your recaptcha key]">
    <YourReCaptchaComponent />
  </GoogleReCaptchaProvider>,
  document.getElementById('app')
);

I'm confused how I am supposed to use const token = executeRecaptcha("login_page"). I don't currently understand how developers should use this token. Isn't there a "score" associated with this token, whereby potential bots will be disallowed from using the page?

How do I verify this token and work with it? Any help appreciated.


Solution

  • The score is associated with the token but that'll be produced when you're doing the actual backend verification request with the token itself. Step 3 of this paragraph

    In a gist:

    Here's a node example with promises . You may just aswell simply make use of fetch

        import * as request from 'request'; // from "web-request": "^1.0.7",
        
        async check(recaptchaResponse: string, remoteAddress: string): Promise<boolean> {
         const secretKey = "";
            return new Promise<boolean>((resolve, reject) => {
              const verificationUrl = 'https://www.google.com/recaptcha/api/siteverify?secret=' + secretKey + '&response=' + recaptchaResponse + '&remoteip=' + remoteAddress;
              request(verificationUrl
                , function(error, response, body) {
                  if (error) {
                    return reject(false);
                  }
                  if (response.statusCode !== 200) {
                    return reject(false);
                  }
        
                  body = JSON.parse(body);
                  const passCaptcha = !(body.success !== undefined && !body.success);
                  resolve(passCaptcha);
                });
            });
          }
    

    Here's an express middleware to delegate the whole process

    e.g.:

        app.post('/', function(req, res){
          recaptcha.verify(req, function(error, data){
            if (!req.recaptcha.error) {
              // success code
            } else {
              // error code
            }
          });
        });
    
        {
          "success": true,
        [...]
          "score": 0.9,
          "action": "examples/v3scores",
          "error-codes": []
        }