将reCAPTCHA v2 API添加到网页中,我无法让它工作。我已经将密钥配置为在html页面中添加了验证码
<!-- Google reCAPTCHA -->
<script th:src="@{https://www.google.com/recaptcha/api.js}"></script>
然后是div
元素
<div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXX"></div>
在服务器端(使用Spring)
@RequestMapping(value = "/contact", method = RequestMethod.POST)
public Callable<String> contactQuery(final @ModelAttribute("contact") @Valid ContactForm contactForm,
final @RequestParam("g-recaptcha-response") String captchaResponse, final BindingResult bindingResult,
final Model model) {
.....
}
然后在另一个班级
@Service
public class ReCaptchaResponseVerfier {
@Resource
private Environment environment;
private static final Logger LOGGER = LoggerFactory.getLogger(ReCaptchaResponseVerfier.class);
@Async
public Future<GoogleCaptchaResponseData> isCaptchaResponseValid(String captchaResponse) throws InterruptedException,
ExecutionException {
LOGGER.debug(" Validating captcha {}", captchaResponse);
if (captchaResponse.isEmpty()) {
GoogleCaptchaResponseData response = new GoogleCaptchaResponseData();
response.setSuccess(false);
response.setErrorCodes("The \"I am not a robot\" genie says you didn't verify, please do so.");
return new AsyncResult<GoogleCaptchaResponseData>(response);
}
AsyncRestTemplate restTemplate = new AsyncRestTemplate();
Map<String, String> uriVariables = new HashMap<String, String>();
ListenableFuture<ResponseEntity<GoogleCaptchaResponseData>> futureResponse = restTemplate.postForEntity(
"https://www.google.com/recaptcha/api/siteverify", buildCaptachRequest(captchaResponse),
GoogleCaptchaResponseData.class);
GoogleCaptchaResponseData response;
response = futureResponse.get().getBody();
return new AsyncResult<GoogleCaptchaResponseData>(response);
}
private HttpEntity<GoogleCaptchaRequestData> buildCaptachRequest(String captchaResponse) {
GoogleCaptchaRequestData request = new GoogleCaptchaRequestData();
request.setResponse(captchaResponse);
request.setSecret(environment.getProperty("google.recaptcha.secret"));
return new HttpEntity<GoogleCaptchaRequestData>(request);
}
但是,我总是获得成功:即使验证码在页面上匹配,也会出现错误的响应。