karser/karser-recaptcha3-bundle
Composer 安装命令:
composer require karser/karser-recaptcha3-bundle
包简介
Google ReCAPTCHA v3 for Symfony
关键字:
README 文档
README
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.
Getting reCAPTCHA v3 key and secret
Register reCAPTCHA v3 keys here.
Installation
With composer, require:
composer require karser/karser-recaptcha3-bundle
Version compatibility
| 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.
Configuration without symfony/flex:
1. Register the bundle
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(), ); }
2. Add configuration files
# 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.5
Add your site key and secret to your .env file:
###> karser/recaptcha3-bundle ###
RECAPTCHA3_KEY=my_site_key
RECAPTCHA3_SECRET=my_secret
###< karser/recaptcha3-bundle ###
Usage
How to integrate re-captcha in Symfony form:
<?php use Karser\Recaptcha3Bundle\Form\Recaptcha3Type; use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3; class TaskType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('captcha', Recaptcha3Type::class, [ 'constraints' => new Recaptcha3(), 'action_name' => 'homepage', 'script_nonce_csp' => $nonceCSP, 'locale' => 'de', ]); } }
Notes:
- The
action_nameparameter 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. - The
script_nonce_cspparameter is optional. You must use the same nonce as in your Content-Security Policy header. - The
localeparameter is optional. It defaults to English and controls the language on the reCaptcha widget.
How to use reCAPTCHA globally (meaning even in China):
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'
How can I set the captcha language for different locales?
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'
How to get the ReCaptcha score:
Inject the Recaptcha3Validator and call getLastResponse()->getScore() after the form was submitted:
<?php use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3Validator; class TaskController extends AbstractController { public function new(Request $request, Recaptcha3Validator $recaptcha3Validator): Response { //... $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { //... $score = $recaptcha3Validator->getLastResponse()->getScore(); //... } //... } }
How to integrate re-captcha in API method:
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:
<?php namespace App\Dto; final class UserSignupRequest { /** @var string|null */ public $email; /** @var string|null */ public $captcha; }
And to add the validation constraint:
#config/validator/validation.yaml App\Dto\UserSignupRequest: properties: email: - NotBlank: ~ - Email: { mode: strict } captcha: - Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3: ~
On frontend part you need to submit the captcha token along with email. You can obtain the captcha token either on page load or on form submit.
<script src="https://www.google.com/recaptcha/api.js?render=<siteKey>"></script> <script> const siteKey = '*****************-**-******-******'; //either on page load grecaptcha.ready(function() { grecaptcha.execute(siteKey, { action: 'homepage' }).then(function(token) { //the token will be sent on form submit $('[name="captcha"]').val(token); //keep in mind that token expires in 120 seconds so it's better to add setTimeout. }); }); //or on form post: grecaptcha.ready(function() { grecaptcha.execute(siteKey, { action: 'homepage' }).then(function(token) { //submit the form return http.post(url, {email, captcha: token}); }); }); </script>
How to show errors from the captcha's response
Just add the {{ errorCodes }} variable to the message template:
$formBuilder->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 }}']),
])
How to deal with functional and e2e testing:
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=0
How to set the threshold from PHP dynamically rather from the .yaml config or .env?
You 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); } }
How to resolve IP propertly when behind Cloudflare:
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:
<?php declare(strict_types=1); namespace App\Service; use Karser\Recaptcha3Bundle\Services\IpResolverInterface; use Symfony\Component\HttpFoundation\RequestStack; class CloudflareIpResolver implements IpResolverInterface { /** @var IpResolverInterface */ private $decorated; /** @var RequestStack */ private $requestStack; public function __construct(IpResolverInterface $decorated, RequestStack $requestStack) { $this->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'
Symfony HttpClient integration
If you have a dependency on symfony/http-client in your application then it will be automatically wired
to use via RequestMethod/SymfonyHttpClient.
Troubleshooting checklist
Make sure you setup recaptcha key/secret of version 3.
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.

Make sure you are seeing this in the html of your rendered form
<input type="hidden" id="form_captcha" name="form[captcha]" /><script>
var recaptchaCallback_form_captcha = function() {
grecaptcha.execute('<YOUR-RECAPTCHA-KEY>', {action: 'landing'}).then(function(token) {
document.getElementById('form_captcha').value = token;
});
};
</script><script src="https://www.google.com/recaptcha/api.js?render=<YOUR-RECAPTCHA-KEY>&onload=recaptchaCallback_form_captcha" async defer></script>
</form>
Make sure you don't have javascript errors in the browser console
Testing
composer update
vendor/bin/phpunit
karser/karser-recaptcha3-bundle 适用场景与选型建议
karser/karser-recaptcha3-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.63M 次下载、GitHub Stars 达 186, 最近一次更新时间为 2019 年 03 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「symfony」 「security」 「recaptcha」 「validation」 「google」 「Forms」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 karser/karser-recaptcha3-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 karser/karser-recaptcha3-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 karser/karser-recaptcha3-bundle 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
The bundle for easy using json-rpc api on your project
Client library for reCAPTCHA with proxy support, a free service that protects websites from spam and abuse.
Diese Contao 4 Erweiterung stellt Google reCAPTCHA V2 in Form eines neuen Formularfeldes im Formulargenerator bereit. This extension provides Google reCAPTCHA V2 in the form of a new form field in the form generator of Contao Open Source CMS.
Provide a way to secure accesses to all routes of an symfony application.
A simple and easy to use Google ReCaptcha v3 package for Laravel
It's a barebone security class written on PHP
统计信息
- 总下载量: 2.63M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 187
- 点击次数: 35
- 依赖项目数: 9
- 推荐数: 2
其他信息
- 授权协议: MIT
- 更新时间: 2019-03-19
