gpt4 book ai didi

javascript - reCaptcha v3 处理分数回调

转载 作者:可可西里 更新时间:2023-10-31 22:50:41 26 4
gpt4 key购买 nike

我关注了recaptcha v3 example并设法让它返回一个带有页面分数的回调,类似于他们的 demo .

我不明白的是如何处理返回的分数。

我明白,成功是建立在阈值之上的。使用 github 包,后端验证将 json(失败或成功)返回给前端。我是否应该使用 javascript 在前端处理失败或成功?如果浏览器有 javascript 怎么办禁用?

我想在所有页面上使用 recaptcha v3 并在一段时间内阻止被认为是机器人的用户。

我正在使用 laravel 但我无法弄清楚如何在中间件或其他地方处理验证,以便在用户没有 token (javascript 被禁用)或被认为是用户时阻止他们机器人。

最佳答案

reCAPTCHA token 应在服务器端进行验证。首先,将生成的 token 附加到您的表单中:

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')
});
});

然后当您在 Controller 上捕获输入时,您可以使用自定义表单请求:

<?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;
}
...

}

g-recaptcha-response 字段是必需的,因此如果用户禁用 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!";
}
}

接下来,在您的 Controller 中使用上面的表单请求:

public function processContactForm(ContactFormRequest $request)
{
...
}

希望这对您有所帮助。

关于javascript - reCaptcha v3 处理分数回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52334269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com