Tuesday, July 7, 2015

How to add Captcha in Java Using Google new reCaptcha
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


Recommended article : MintEye gives Captcha Java API for Web Application


How reCaptcha Works

  • Developer has to register their website for Google recaptcha. Then developer will get application key.
  • Developer has to integrate reCaptcha with registered website.
  • Whenever user clicks on "I am not a robot, Google reCaptcha script will generate input value with name g-recaptcha-response. 
  • Whenever user submits the form, The website server receives code with parameter recaptcha-response.
  • 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 or you can check this tutorial also

Get reCaptcha Key


 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 sidevalidation.

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 applicationsecret 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 
 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);
    }
}
If You Enjoyed This, Take 5 Seconds To Share It

No comments:

Post a Comment