Thursday, October 9, 2008

reCaptcha Implementation

Description:
reCaptcha is one of the Captcha implementation. In this article I will mention step by step implementation in a java application and the issues I've faced while using reCaptcha.

Implementation Steps:
  1. Go to reCaptcha site 'http://recaptcha.net/
  2. Open an account and create site
  3. Get public key and private key
  4. In UI page (HTML page or JSP) where the form is available and data entry need to be verified, add following code block - 

    --- Code Start ---
    <-script type="text/javascript" src="http://api.recaptcha.net/challenge?k=(set your the public key)">
    <-/script>
    <-noscript>
    <-iframe src="http://api.recaptcha.net/noscript?k=(set your the public key)" height="300" width="500" frameborder="0"><-/iframe>

    <-textarea name="recaptcha_challenge_field" rows="3" cols="40"><-/textarea>  
    <-input type="hidden" name="recaptcha_response_field" value="manual_challenge">
    --- Code End ---

    Note: remove '-' at the begining of HTML tags which is there to make the HTML tag visible.


  5. In the server side code (servlet, struts Action etc.),  write code as below-

    ------------------
    --- Code Start ---
    ------------------

    -- Import section --
    import net.tanesha.recaptcha.ReCaptchaImpl;
    import net.tanesha.recaptcha.ReCaptchaResponse;

    -- Code to get form value from UI and reCaptcha API call --
    String challenge = request.getParameter("recaptcha_challenge_field");
    String responseValue = request.getParameter("recaptcha_response_field"); 
    String remoteAddr = request.getRemoteAddr(); 
    ReCaptchaImpl reCaptcha = new ReCaptchaImpl(); 
    reCaptcha.setPrivateKey("6LepaQMAAAAAANSLGCL-mZGEEnimfywUSztxLVRg");
    ReCaptchaResponse reCaptchaResponsereCaptcha.checkAnswer(remoteAddr, challenge, responseValue );
    boolean valid = reCaptchaResponse.isValid();

    if (valid) { /* Your code */}
     else { /* Your code */}
    ------------------
    --- Code End ---
    ------------------ 
Issue List

Issue 1:
reCaptcha doesn't support IPv6 yet. So, need to be careful when getting IP address of machine and passing to reCaptcha API.

Solution 1:
If IPv6 isn't explicitly needed, uninstall IPv6 protocol from the machine
Solution 2:
Configure JVM to work with IPv4 protocol stack. The parameter needs to be set is "-Djava.net. preferIPv4Stack=true". 

Issue 2:
reCaptcha shows two words to validate but in practical, second word doesn't have any effect. This is a known issue in reCaptcha.

Resources:
1.  reCaptcha web site: 'http://recaptcha.net/'

No comments: