Recaptcha V3 with Symfony

reCAPTCHA v3 is a new version that detects abusive traffic on your website without user friction. It returns a score for every request you send to reCAPTCHA and gives you more flexibility to fight spam and abuse in your own way.

Contrary to version 2, the Recaptcha v3 has been implemented a new workflow.

When creating a new google reCaptcha project. this will generate for you site key and secret key which has been mentioned in the workflow above.

First, you need to request the token using the site key. In my case, I’m using angular application adopting the Angular component for Google reCAPTCHA

export class SearchFormComponent implements OnInit {

  constructor(private recaptchaV3Service: ReCaptchaV3Service) {}

  ngOnInit() {}

  search() {

      this.recaptchaV3Service.execute('my-action')
        .subscribe((token) => console.log(token));
    }

}

In case you are using simple javascript in the template engine, you need to include the google Recaptcha script in your file

 <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
  <script>
  grecaptcha.ready(function() {
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
         ...
      });
  });
  </script>

For more details, please reffer to the official documentation

Since the token is rendered by the google ReCaptcha server, it should be validated by sending it to your backend application. In my case, I’m using Symfony ) and verify it using the secret key already generated in the google Recaptcha administration of the created account.

First, you need to include the google Recaptcha client by Composer.

composer require google/recaptcha

There is a lot of implementation to do the task . may be using validator/constraint Symfony behavior or just a simple service.

Let’s go for the service class that will care of the token validation logic.

class RecaptchaV3Service
{
    /** @var String*/
    protected $scorethreshold;

    /** @var ReCaptcha*/
    protected  $recaptchaClient;

    /**
     * RecaptchaV3Service constructor.
     * @param String $secret
     * @param String $scorethreshold
     */
    public function __construct(String $secret,String $scorethreshold)
    {
        $this->scorethreshold = $scorethreshold;
        $this->recaptchaClient = new ReCaptcha($secret);
    }

    /**
     * @param $token
     * @return mixed
     * @throws InvalidRecaptchaException
     */
    public function verify($token)
    {
        $response = $this->recaptchaClient->setScoreThreshold($this->scorethreshold)
            ->verify($token);
        return $response->isSuccess();
    }
}
//parameters.yml
parameters :
    recaptcha_secret: 'my google recaptche secret key'
    recaptcha_score_threshold: 0.3

The Google Recaptcha v3 threshold varies between 0 and 1

Example: if the threshold is set to 0.3, that means above 0.7, the Recaptcha is validated true. a manner to set the tolerance value.

Based on this threshold, the Google Recaptcha server will return a boolean which represent the validation you requested.

Integration tests

Probably, you are using integration/unit tests over your project, so while you are integrating the Google Recaptcha V3, you may have an integration test about that. In another way, you need to verify the Recaptcha token to be always valid. Google has already taken care of that by generating the couple site key/secret key that will always return a success validation using them.

Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI

Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

Also, don’t forget to assign the threshold value to 0.

For more information, please refer the official documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *