Prove you are not a robot

Hi guys

What are my options in Vaadin 7.4 for verifying that the user is not a robot?

I’ve looked at
ReCaptcha Add-On
but it seems outdated now that Google has left ReCaptcha v1 in favour of ReCaptcha v2.

The solution I’m after doesn’t have to be based on Captcha-like stuff. I’m open to all suggestions.

Surely others must have had the same requirement. :slight_smile:

Thanks.

Peter

After a long search I could not find, and now have the following solution even written. hopefully it helps.

Edit 2015-11-19: get the new version at
https://www.epicsoft.de/recaptcha-v2-und-vaadin-7/

package [...]


import java.io.IOException;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.annotations.JavaScript;
import com.vaadin.server.Page;
import com.vaadin.ui.CustomLayout;

/*
 * The MIT License - https://opensource.org/licenses/MIT
 *
 * Copyright (c) 2015 epicsoft.de / Alexander Schwarz
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

/**
 * Using Google reCaptcha v2 in Vaadin 7<br>
 * Content-Security-Policy see https://developers.google.com/recaptcha/docs/faq <br>
 * Dependencies: <br>
 * - SLF4J API Module <br>
 * - Apache HttpClient <br>
 * - Jackson Databind <br>
 * <br>
 * Copyright epicsoft.de @author Alexander Schwarz
 *
 * @version 1.0
 */
@JavaScript("https://www.google.com/recaptcha/api.js")
public class ReCaptchaV2 extends CustomLayout {

    private static transient final Logger log = LoggerFactory.getLogger(ReCaptchaV2.class);

    private static final long serialVersionUID = -2566236582190045142L;

    // test public and private keys see https://developers.google.com/recaptcha/docs/faq
    private static final String TEST_SITE_KEY = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI";
    private static final String TEST_SECRET_KEY = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe";
    // placeholder for reCaptcha
    private static final String DIV = "<div class=\"g-recaptcha\" data-sitekey=\"{SITE_KEY}\" data-callback=\"reCaptchaSuccessCallback\"></div>";
    // URL for verification
    private final static String VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify?secret={key}&response={res}";
    // optional part of verify URL
    private final static String VERIFY_URL_IP = "&remoteip={ip}";

    // public and private key. testing as default
    private String siteKey = TEST_SITE_KEY;
    private String secretKey = TEST_SECRET_KEY;
    // response
    private String response;

    /**
     * default constructor. Use only for Test !!!
     */
    public ReCaptchaV2() {
        this(TEST_SITE_KEY, TEST_SECRET_KEY);
    }

    /**
     * Constructor for productive mode, use your own public and private key. see https://www.google.com/recaptcha
     *
     * @param keySite
     * @param keySecret
     */
    public ReCaptchaV2(final String keySite, final String keySecret) {
        super();
        this.siteKey = keySite;
        this.secretKey = keySecret;
        this.init();
    }

    /**
     * Init the Layout. Insert custom HTML (Placeholder) and create JavaScript-Callback for response.
     */
    private void init() {
        // custom HTML
        final String html = DIV.replace("{SITE_KEY}", this.siteKey);
        this.setTemplateContents(html);
        // JavaScript callback
        com.vaadin.ui.JavaScript.getCurrent().addFunction("reCaptchaSuccessCallback", arguments -> {
            this.response = arguments.asString();
        });
    }

    /**
     * check if reCaptcha answer is valid
     *
     * @return {@link Boolean}
     */
    public boolean isValid() {
        boolean success = false;
        // Check only, when responce available
        if (this.response != null) {
            // build verify URL
            String url = VERIFY_URL.replace("{key}", this.secretKey).replace("{res}", this.response);
            // Current client ip-address
            final String ipAddress = Page.getCurrent().getWebBrowser().getAddress();
            if (ipAddress != null) {
                url += VERIFY_URL_IP.replace("{ip}", ipAddress);
            }

            try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
                final HttpPost post = new HttpPost(url);
                final String body = httpClient.execute(post, response -> {
                    final int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        final HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    }
                    throw new ClientProtocolException("Unexpected response status: " + status);
                });

                @SuppressWarnings("unchecked")
                final HashMap<String, Object> result = new ObjectMapper().readValue(body, HashMap.class);
                success = (boolean) result.get("success");
            } catch (final IOException e) {
                log.error(e.getMessage(), e);
            }
        } else {
            log.error("response is empty");
        }
        return success;
    }
}

It’s works fine, but when I close and open the window again the reChapta is not show any more …

The following method does not help …
public void reset() {
JavaScript.getCurrent().execute(“grecaptcha.reset()”);
}

Any hind will be appreciated.

the new version 1.3 fixes the problem with the new method “render”.

https://www.epicsoft.de/recaptcha-v2-und-vaadin-7/