
recaptcha v3 不返回“通过/失败”二值结果,而是提供 0.0–1.0 的信任评分;开发者必须主动检查 `score` 字段并结合业务场景设定阈值(推荐 ≥0.7),仅依赖 `success: true` 会导致高风险请求被误放行。
reCAPTCHA v3 的核心设计逻辑与传统验证码截然不同:它不中断用户流程,而是在后台持续评估用户行为(如鼠标轨迹、页面停留时间、交互节奏、设备指纹等),最终返回一个连续型信任分数(score),范围是 0.0(极可能是机器人)到 1.0(极可能是真实人类),默认阈值建议为 0.7(即 70% 置信度)。
⚠️ 关键误区警示:
“success”: true 仅代表 Token 校验合法且未过期(例如未被篡改、未重复使用、未超时),绝不表示用户可信。google 明确文档指出:
“The score is not a binary pass/fail value. It’s a continuous value between 0.0 and 1.0. You must define your own thresholds based on your site’s risk tolerance.”
因此,您当前的代码存在严重安全漏洞——只要 token 有效就放行,完全忽略了实际风险评分。
✅ 正确做法:在服务端校验中强制检查 score 并设置业务敏感阈值。以下是优化后的 php 示例(含错误处理与日志建议):
if (!isset($_POST['grecaptcharesponse'])) { http_response_code(400); header('Content-Type: application/json'); echo json_encode(['error' => 'Missing reCAPTCHA token']); exit; } $secret = 'your_secret_key_here'; $token = $_POST['grecaptcharesponse']; $url = "https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$token}"; $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => true, ]); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); // Step 1: 验证 API 基础响应有效性 if (!$result || !isset($result['success']) || $result['success'] !== true) { error_log('[reCAPTCHA] Invalid API response: ' . print_r($result, true)); http_response_code(400); header('Content-Type: application/json'); echo json_encode(['error' => 'reCAPTCHA verification failed: invalid response']); exit; } // Step 2: 强制检查 score(v3 的核心判断依据) $score = $result['score'] ?? 0.0; $action = $result['action'] ?? ''; // 推荐阈值:注册场景建议 ≥0.7;登录可略低(如 0.5),敏感操作(如支付)应 ≥0.9 $threshold = 0.7; if ($score < $threshold) { error_log("[reCAPTCHA] Low score {$score} for action '{$action}' (threshold {$threshold})"); http_response_code(403); header('Content-Type: application/json'); echo json_encode([ 'error' => 'Verification failed. Suspicious activity detected.', 'score' => $score, 'suggestion' => 'Consider additional verification (e.g., email confirm)' ]); exit; } // ✅ 通过验证:继续执行注册逻辑 // ... your registration code here ...
? 补充最佳实践:
- 记录 action 字段:确保前端调用 grecaptcha.execute(siteKey, {action: ‘register’}) 时指定语义化动作(如 ‘register’, ‘login’, ‘contact’),便于后端按场景差异化设阈值;
- 启用 hostname 校验:在 google Cloud console 中绑定合法域名,防止 token 被盗用至其他站点;
- 定期审查日志中的低分请求模式:若大量请求集中在特定 action 或 IP 段,可能需配合速率限制或挑战升级(如 fallback 到 reCAPTCHA v2);
- 避免硬编码阈值:生产环境建议将阈值配置化(如数据库或配置中心),便于 A/B 测试与动态调整。
总之,reCAPTCHA v3 的价值不在“能否验证”,而在“多大程度可信”。忽略 score 就等于放弃其智能风控能力——请始终以分数为决策核心,而非仅凭 success 字段做安全判断。