Vic*_*rdb 10 javascript php recaptcha laravel
我按照recaptcha v3示例进行了操作,并设法让它返回一个带有页面分数的回调,类似于他们的演示.
我不明白的是如何处理返回的分数.
我知道成功是基于门槛.使用github包后端验证将json(失败或成功)返回到前端.我应该使用javascript处理前端的失败或成功吗?如果浏览器禁用了javascript怎么办?
我想在所有页面上使用recaptcha v3并阻止用户考虑机器人一段时间.
我正在使用laravel但我无法弄清楚如何在中间件或其他地方处理验证,以便在用户没有令牌(javascript被禁用)或他们被视为机器人时阻止用户.
reCAPTCHA 令牌应在服务器端进行验证。首先,将生成的令牌附加到您的表单中:
grecaptcha.ready(function() {
grecaptcha.execute('{{env('RECAPTCHA_V3_PUBLIC_KEY')}}', {action: 'contactform'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
name: 'g-recaptcha-response',
value: token
}).prependTo('.contact-form')
});
});
Run Code Online (Sandbox Code Playgroud)
然后,当您捕获控制器上的输入时,您可以使用自定义表单请求:
<?php
namespace App\Http\Requests;
use App\Rules\RecaptchaV3;
use Illuminate\Foundation\Http\FormRequest;
class ContactFormRequest extends FormRequest
{
public function rules()
{
$rules = [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
'g-recaptcha-response' => ['required', new RecaptchaV3],
];
return $rules;
}
...
}
Run Code Online (Sandbox Code Playgroud)
g-recaptcha-response
字段是required
这样的,如果用户禁用 JS,他们将在验证表单输入时收到错误。
接下来g-recaptcha-response
我们应用自定义验证规则:RecaptchaV3。
这是我的实现:
<?php
namespace App\Rules;
use GuzzleHttp\Client;
use Illuminate\Contracts\Validation\Rule;
class RecaptchaV3 implements Rule
{
public function passes($attribute, $value)
{
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_V3_PRIVATE_KEY'),
'response' => $value,
'remoteip' => $_SERVER['REMOTE_ADDR'],
]
]);
$decoded = json_decode($response->getBody());
return $decoded->success;
}
public function message()
{
return "You didn't pass reCAPTCHA challenge!";
}
}
Run Code Online (Sandbox Code Playgroud)
接下来,在您的控制器中使用上面的表单请求:
public function processContactForm(ContactFormRequest $request)
{
...
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
归档时间: |
|
查看次数: |
5464 次 |
最近记录: |