Google ReCAPTCHA v3 for Symfony
reCAPTCHA v3 returns a score for each request without user friction. The score is based on interactions with your site (1.0 is very likely a good interaction, 0.0 is very likely a bot) and enables you to take an appropriate action for your site.
Register reCAPTCHA v3 keys here.
With composer, require:
composer require karser/karser-recaptcha3-bundle
| Bundle Version | Symfony Version | PHP Version |
|---|---|---|
| 0.3.x | 6.4, 7.x, 8.x | ≥8.1 |
| 0.2.x | 3.4, 4.x, 5.x, 6.x, 7.x | ≥7.4 |
| 0.1.x | 3.4, 4.x, 5.x | ≥7.1 |
You can quickly configure this bundle by using symfony/flex.
Symfony 6.4/7.x/8.x Version:
Register bundle into config/bundles.php:
return [
//...
Karser\Recaptcha3Bundle\KarserRecaptcha3Bundle::class => ['all' => true],
];Older Symfony Versions (3.x/4.x/5.x): Please use bundle version 0.2.x for these Symfony versions.
For Symfony 3, register bundle into app/AppKernel.php:
public function registerBundles()
{
return array(
// ...
new Karser\Recaptcha3Bundle\KarserRecaptcha3Bundle(),
);
}# config/packages/karser_recaptcha3.yaml (or app/config/config.yml if using Symfony3)
karser_recaptcha3:
site_key: '%env(RECAPTCHA3_KEY)%'
secret_key: '%env(RECAPTCHA3_SECRET)%'
score_threshold: 0.5Add your site key and secret to your .env file:
###> karser/recaptcha3-bundle ###
RECAPTCHA3_KEY=my_site_key
RECAPTCHA3_SECRET=my_secret
###add('captcha', Recaptcha3Type::class, [
'constraints' => new Recaptcha3(),
'action_name' => 'homepage',
'script_nonce_csp' => $nonceCSP,
'locale' => 'de',
]);
}
}Notes:
action_name parameter is reCAPTCHA v3 action which identifies the submission of this particular form in the Google reCAPTCHA dashboard, and confirming it is as expected in the backend is a recommended extra security step.script_nonce_csp parameter is optional. You must use the same nonce as in your Content-Security Policy header.locale parameter is optional. It defaults to English and controls the language on the reCaptcha widget.Use 'www.recaptcha.net' host in your code when 'www.google.com' is not accessible.
# config/packages/karser_recaptcha3.yaml (or app/config/config.yml if using Symfony3)
karser_recaptcha3:
host: 'www.recaptcha.net' # default is 'www.google.com'You can control the language in the small widget displayed by setting the locale in the options above.
To change the error messages, you should install the Symfony Translation component.
Then replace the validation text with the translation keys for the message and messageMissingValue options:
$builder->add('captcha', Recaptcha3Type::class, [
'constraints' => new Recaptcha3 ([
'message' => 'karser_recaptcha3.message',
'messageMissingValue' => 'karser_recaptcha3.message_missing_value',
]),
]);Add English, Spanish, or any other translation:
# translations/validators/validators.en.yaml
karser_recaptcha3.message: 'Your computer or network may be sending automated queries'
karser_recaptcha3.message_missing_value: 'The captcha value is missing'
# translations/validators/validators.es.yaml
karser_recaptcha3.message: 'Es posible que su computadora o red esté enviando consultas automatizadas'
karser_recaptcha3.message_missing_value: 'Falta el valor de captcha'Inject the Recaptcha3Validator and call getLastResponse()->getScore() after the form was submitted:
handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
//...
$score = $recaptcha3Validator->getLastResponse()->getScore();
//...
}
//...
}
}The idea is to require the frontend to submit the captcha token, so it will be validated on server side.
First you need to add the captcha field to your transport entity:
add('captcha', Recaptcha3Type::class, [
'constraints' => new Recaptcha3(['message' => 'There were problems with your captcha. Please try again or contact with support and provide following code(s): {{ errorCodes }}']),
])Recaptcha won't allow you to test your app efficiently unless you disable it for the environment you are testing against.
# app/config/config.yml (or config/packages/karser_recaptcha3.yaml if using Symfony4)
karser_recaptcha3:
enabled: '%env(bool:RECAPTCHA3_ENABLED)%'#.env.test or an environment variable
RECAPTCHA3_ENABLED=0You should inject @karser_recaptcha3.google.recaptcha in your service and call setScoreThreshold method.
#services.yaml
App\Services\YourService:
arguments: ['@karser_recaptcha3.google.recaptcha']#App/Services/YourService.php
use Karser\Recaptcha3Bundle\ReCaptcha\ReCaptcha;
class YourService {
private $reCaptcha;
public function __construct(ReCaptcha $reCaptcha) {
$this->reCaptcha = $reCaptcha;
}
public function yourMethod() {
$this->reCaptcha->setScoreThreshold(0.7);
}
}From the Cloudflare docs: To provide the client (visitor) IP address for every request to the origin, Cloudflare adds the CF-Connecting-IP header.
"CF-Connecting-IP: A.B.C.D"So you can implement custom IP resolver which attempts to read the CF-Connecting-IP header or fallbacks with the internal IP resolver:
decorated = $decorated;
$this->requestStack = $requestStack;
}
public function resolveIp(): ?string
{
return $this->doResolveIp() ?? $this->decorated->resolveIp();
}
private function doResolveIp(): ?string
{
$request = $this->requestStack->getCurrentRequest();
if ($request === null) {
return null;
}
return $request->server->get('HTTP_CF_CONNECTING_IP');
}
}Here is the service declaration. It decorates the internal resolver:
#services.yaml
services:
App\Service\CloudflareIpResolver:
decorates: 'karser_recaptcha3.ip_resolver'
arguments:
$decorated: '@App\Service\CloudflareIpResolver.inner'
$requestStack: '@request_stack'If you have a dependency on symfony/http-client in your application then it will be automatically wired
to use via RequestMethod/SymfonyHttpClient.
Also, make sure you added the domain you use in the recaptcha settings. Usually dev domain differs from the production one, so better to double check.
composer update
vendor/bin/phpunitNo open issues yet, or sync has not completed.