eighteen73 / laravel-turnstile
将Cloudflare Turnstile验证添加到Laravel表单中
Requires
- illuminate/support: ^9.0|^10.0|^11.0
Requires (Dev)
- laravel/pint: ^1.2
README
这个Laravel包简化了在您的网站上实现Cloudflare Turnstile(一种CAPTCHA替代方案)的过程。
安装
通过Composer安装包。
composer require eighteen73/laravel-turnstile
然后发布配置文件到您的项目中。
php artisan vendor:publish --tag=turnstile-config
turnstile凭证
请参阅Cloudflare Turnstile文档,了解如何获取turnstile站点密钥和密钥。
一旦您在Cloudflare账户中设置了turnstile,您需要将两个新值添加到项目的.env文件中。
TURNSTILE_KEY=your-site-key TURNSTILE_SECRET=your-secret-key
表单标记
首先,您需要确保turnstile JavaScript已包含在您的网站上。turnstile分析会话期间显示的各种遥测和客户端行为,因此此脚本应包含在整个网站上。
使用如下Blade指令@turnstileScripts
<html> <head> <!-- It could go here if you prefer --> </head> <body> <!-- The rest of your template --> @turnstileScripts </body> </html>
然后,当您希望使用turnstile保护表单时,只需包含以下指令和错误响应代码
<form action="..." method="post"> <!-- The rest of your form --> @turnstile @error('cf-turnstile-response') <div class="alert alert-danger">{{ $message }}</div> @enderror </form>
验证模式
有两种方式可以验证您的表单提交。默认启用的是“中间件”模式,它是完全自动的,但您可能会发现它太有限了,在这种情况下,您应该启用“验证”模式。
在项目的config/turnstile.php文件中更改验证模式。
通过中间件
这将自动检查web中间件组中的每个请求的turnstile响应代码。如果找到,它将在允许请求继续之前验证它。
如果需要保护除web之外的中间件组或需要更多控制turnstile错误报告的方式/时间,则此验证模式不是最佳选择。例如,如果您希望将turnstile与其他表单输入字段一起验证(以便可以一起显示所有错误消息),则应使用下面的“验证”模式。
通过表单验证
这提供了更多的灵活性,但需要您手动将turnstile响应代码添加到表单验证规则中,无论它在哪里使用。
例如
use Eighteen73\Turnstile\Rules\Turnstile; $request->validate([ 'email' => 'required|email', 'password' => 'required', 'cf-turnstile-response' => [new Turnstile], ]);
许可证
MIT许可证(MIT)。有关更多信息,请参阅许可证文件。