Google launched new reCaptcha for effective detection of robots. Every day hackers decrypting captchas. It became difficult for organizations to get protection from bots. Google has given solution to this problem with new reCaptcha. In this article, I am going to explain the implementation of reCaptcha with Java

How reCaptcha Works

  1. Developer has to register their website for Google recaptcha. Then developer will get application key.
  2. Developer has to integrate reCaptcha with registered website.
  3. Whenever user clicks on "I am not a robot, Google reCaptcha script will generate input value with name g-recaptcha-response
  4. Whenever user submits the form, The website server receives code with parameter recaptcha-response.
  5. Now developer has to verify the code at server side by sending one get request to google recaptcha server with application secret key.

Libraries

Get Google GSON Java Library to handle JSON responses.

Get reCaptcha Key

Click here to register your website and get key for your web application
Get key
Here Site key is open, any one can see. Site key will be used in the script of HTML page. Secret key is for only application developer and it is for contacting google server side validation.

HTML Code

Add google reCaptcha script

<script src='https://www.google.com/recaptcha/api.js'></script>

Add reCaptcha DIV

Google script will add input field to this div
<div class="g-recaptcha" data-sitekey="6Lcsyf4SAAAAABLp3hPq6afXNfsXGxYDjCzwpbbJ"></div>

Observe below HTML code

In this below HTML google reCaptcha DIV was enclosed by form. Whenever user clicks on submit button reCaptcha input field will be submitted along with form input fields.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google New reCaptcha using Java</title>
</head>
<script src='https://www.google.com/recaptcha/api.js'></script>
<style type='text/css'>
.field {
    padding: 0 0 10px 0;
}

.label {
    padding: 3px 0;
    font-weight: bold;
}
</style>

<body>
    <div style="text-align: center">
        <h1>Google reCaptcha using Java</h1>
    </div>
    <div style="width: 400px; margin: auto">
        <form action="HandleRecaptcha">
            <h3>Registration Form</h3>
            <div class="field">
                <div class="label">Enter Name</div>
                <input value="" name="name" />
            </div>

            <div class="field">
                <div class="label">Enter Email</div>
                <input name="email" />
            </div>

            <div class="g-recaptcha"
                data-sitekey="6Lcsyf4SAAAAABLp3hPq6afXNfsXGxYDjCzwpbbJ"></div>

            <div class="field">
                <input type="submit" value="submit" />
            </div>

        </form>
    </div>
</body>
</html>

Java Code

CaptchaResponse.java

Pojo class to handle JSON Response
public class CaptchaResponse {
    public boolean success;

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }
}

HandleRecaptcha.java

Once user clicks on submit button, form data will be submitted to Server. Now get g-recaptcha-response parameter value. 
String recap = request.getParameter("g-recaptcha-response");
Now verify the g-recaptcha-response with Google server using your application secret key.
URL url = new URL("https://www.google.com/recaptcha/api/siteverify?secret="+secretParameter+"&response="+recap+"&remoteip="+request.getRemoteAddr());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String line, outputString = "";
BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
    outputString += line;
}
System.out.println(outputString);
Now convert the response into Java Object and verify whether the input is from robot or human
CaptchaResponse capRes = new Gson().fromJson(outputString, CaptchaResponse.class);
if(capRes.isSuccess()) {
    // your logic - Human
} else {
    // your logic - Robot
}
Complete servlet code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class HandleRecaptcha extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String secretParameter="Your Application Secret Code Here";
       
    public HandleRecaptcha() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Get input parameter values (form data)
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String recap = request.getParameter("g-recaptcha-response");
        
        // Send get request to Google reCaptcha server with secret key  
        URL url = new URL("https://www.google.com/recaptcha/api/siteverify?secret="+secretParameter+"&response="+recap+"&remoteip="+request.getRemoteAddr());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        String line, outputString = "";
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            outputString += line;
        }
        System.out.println(outputString);
        
        // Convert response into Object
        CaptchaResponse capRes = new Gson().fromJson(outputString, CaptchaResponse.class);
        request.setAttribute("name", name);
        request.setAttribute("email", email);
        
        // Verify whether the input from Human or Robot 
        if(capRes.isSuccess()) {
            // Input by Human
            request.setAttribute("verified", "true");   
        } else {
            // Input by Robot
            request.setAttribute("verified", "false");
        }
        request.getRequestDispatcher("/response.jsp").forward(request, response);
    }

}

6 comments:

  1. Thanks for the Tutorial.. But can't download the source code provided.. Please do something about that...

    ReplyDelete
    Replies
    1. Modified download settings, you can download the project now, Thanks

      Delete
  2. Will this work when proxy server hiding real application ?

    I don't think so, this must throw UnknownHostException

    Please comment

    ReplyDelete
  3. All the developers come here and get helping material. All the material is here for them because most of the time they missed this the best essays which brings many changes and all these changes are not good for them.

    ReplyDelete

Blogroll

Popular Posts