protected boolean validateRecaptcha( ValidationContext context, boolean success, String captcha, String secret) { HttpClient httpClient = context.getSession().getProvider(HttpClientProvider.class).getHttpClient(); HttpPost post = new HttpPost("https://www.google.com/recaptcha/api/siteverify"); List<NameValuePair> formparams = new LinkedList<>(); formparams.add(new BasicNameValuePair("secret", secret)); formparams.add(new BasicNameValuePair("response", captcha)); formparams.add(new BasicNameValuePair("remoteip", context.getConnection().getRemoteAddr())); try { UrlEncodedFormEntity form = new UrlEncodedFormEntity(formparams, "UTF-8"); post.setEntity(form); HttpResponse response = httpClient.execute(post); InputStream content = response.getEntity().getContent(); try { Map json = JsonSerialization.readValue(content, Map.class); Object val = json.get("success"); success = Boolean.TRUE.equals(val); } finally { content.close(); } } catch (Exception e) { logger.error("Recaptcha failed", e); } return success; }
@Override public void validate(ValidationContext context) { MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters(); List<FormMessage> errors = new ArrayList<>(); boolean success = false; context.getEvent().detail(Details.REGISTER_METHOD, "form"); String captcha = formData.getFirst(G_RECAPTCHA_RESPONSE); if (!Validation.isBlank(captcha)) { AuthenticatorConfigModel captchaConfig = context.getAuthenticatorConfig(); String secret = captchaConfig.getConfig().get(SITE_SECRET); success = validateRecaptcha(context, success, captcha, secret); } if (success) { context.success(); } else { errors.add(new FormMessage(null, Messages.RECAPTCHA_FAILED)); formData.remove(G_RECAPTCHA_RESPONSE); context.getEvent().error(Errors.INVALID_REGISTRATION); context.validationError(formData, errors); return; } }