'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 1:[1]

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:

  • Setup the front-end reCaptcha v3 like you've done and obtain the token
  • Setup a backend validation service in a language of your choice for the verification with your secret key

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
        }
      });
    });
  • The response will then contain the score mentioned and based on that you can take the appropriate action that you wish to, e.g.:
    {
      "success": true,
    [...]
      "score": 0.9,
      "action": "examples/v3scores",
      "error-codes": []
    }

Solution 2:[2]

I find node server implementations for verify your token and get score.

var express = require('express'),                       
bodyParser = require('body-parser'),
  app = express(),
  port = process.env.PORT || 3000;
var fetch = require('node-fetch');
var SECRET_KEY = "<Your Key>";

// enable CORS using npm package
var cors = require('cors');
app.use(cors());

// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

// verify reCAPTCHA response
app.post('/verify', (req, res) => {
  var VERIFY_URL = `https://www.google.com/recaptcha/api/siteverify?secret=${SECRET_KEY}&response=${req.body['g-recaptcha-response']}`;
  return fetch(VERIFY_URL, { method: 'POST' })
    .then(res => res.json())
    .then(json => res.send(json));
});


app.listen(port, () => {
  console.log('Server started on: ' + port);
});

credits: https://github.com/cluemediator/verify-recaptcha-v3-nodejs

Check these articles for more informations - backend implementation - https://www.cluemediator.com/how-to-verify-google-recaptcha-v3-response

you can check frontend implementation either (there is server call) - fronted implementation - https://www.cluemediator.com/how-to-implement-recaptcha-v3-in-react#cabatvrr

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vít Zadina