如何在Grails 2.5.6的注册表单中实现Captcha v3?
在Grails 2.5.6中实现Google reCAPTCHA v3的方案
我之前在Grails 2.5.6项目里手动集成过reCAPTCHA v3,不需要依赖第三方插件(多数插件已不再维护这个老版本),下面是具体实现步骤:
一、前端集成
- 在页面的
<head>区域引入reCAPTCHA v3的脚本,替换成你的site key:
<script src="https://www.google.com/recaptcha/api.js?render=你的Site_Key"></script>
- 给表单添加提交逻辑,调用reCAPTCHA获取验证token,再提交表单:
// 绑定表单提交事件(或直接在按钮点击时触发) document.getElementById('submitBtn').addEventListener('click', function(e) { e.preventDefault(); grecaptcha.ready(function() { // 这里的action参数可以根据页面场景设置,比如'login'/'register' grecaptcha.execute('你的Site_Key', {action: 'submit'}).then(function(token) { // 将token存入隐藏输入框 document.getElementById('recaptchaToken').value = token; // 提交表单 document.getElementById('yourForm').submit(); }); }); });
- 在表单内添加一个隐藏输入框,用于传递token到后端:
<form id="yourForm" action="${createLink(action: 'submitForm')}" method="post"> <!-- 其他表单字段 --> <input type="hidden" id="recaptchaToken" name="recaptchaToken" /> <button type="button" id="submitBtn">提交</button> </form>
二、后端验证
- 先确保项目依赖了HTTP客户端,在
BuildConfig.groovy的dependencies块中添加:
compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.2'
- 在控制器中编写验证方法,调用Google的验证API:
import groovyx.net.http.RESTClient import org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpServletRequest def verifyRecaptcha(String recaptchaToken) { def secretKey = "你的Secret_Key" def verifyUrl = "https://www.google.com/recaptcha/api/siteverify" def request = request as GrailsHttpServletRequest def http = new RESTClient(verifyUrl) try { def response = http.post( body: [ secret: secretKey, response: recaptchaToken, remoteip: request.remoteAddr ] ) // 验证成功且分数达标(score阈值可根据场景调整,比如0.5~0.9) return response.data.success && response.data.score >= 0.5 } catch (Exception e) { log.error("reCAPTCHA验证请求失败", e) return false } }
- 在表单提交的action中调用验证逻辑:
def submitForm() { def recaptchaToken = params.recaptchaToken // 先验证reCAPTCHA if (!recaptchaToken || !verifyRecaptcha(recaptchaToken)) { flash.message = "验证码验证失败,请重试" redirect(action: 'index') return } // 后续处理表单业务逻辑 // ... flash.message = "提交成功" redirect(action: 'index') }
注意事项
- 务必确保Site Key和Secret Key是从Google reCAPTCHA控制台获取,且控制台已配置当前项目的域名
- score阈值可根据业务场景调整:比如登录、支付等高风险场景可以设为0.7以上,注册、留言等场景可设为0.5
- 如果遇到HTTP请求异常,检查项目的网络权限是否允许访问Google的验证API
内容的提问来源于stack exchange,提问作者Javier Antonio Ay Pech
相关产品推荐
相关产品推荐

