Last active
December 26, 2015 10:29
-
-
Save fforbeck/7137371 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 - Create your private and public key for your domain: https://www.google.com/recaptcha/admin/create | |
2 - Displaying the reCAPTCHA Widget: https://developers.google.com/recaptcha/docs/display | |
2.1 - Once configured the script and iframe you need to submit the value of fields to your servlet: | |
- recaptcha_response_field | |
- recaptcha_challenge_field | |
3 - Download and setup de recaptcha lib into your java project: https://code.google.com/p/recaptcha/downloads/list?q=label:java-Latest | |
4 - Implementing the server side recaptcha validation: | |
4.1 - See the ReCaptchaUtil.java: https://gist.github.com/fforbeck/7137371#file-recaptchautil-java | |
4.2 - Here you can find how to verifying the solution: https://developers.google.com/recaptcha/docs/verify |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.apache.commons.lang.StringUtils.isBlank; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import org.apache.log4j.Logger; | |
import net.tanesha.recaptcha.ReCaptchaImpl; | |
import net.tanesha.recaptcha.ReCaptchaResponse; | |
public class ReCaptchaUtil { | |
private Logger logger = Logger.getLogger(ReCaptchaUtil.class); | |
public boolean isValidCaptcha(HttpServletRequest request, HttpServletResponse response) { | |
try { | |
//TODO send the error code to the client | |
final String challenge = request.getParameter("recaptcha_challenge_field"); | |
final String challengeResponse = request.getParameter("recaptcha_response_field"); | |
final String remoteAddr = request.getRemoteAddr(); | |
if (isBlank(challenge) || isBlank(challengeResponse) || isBlank(remoteAddr)) { | |
logger.error("Invalid captcha data { challenge: " + challenge + ", response: " + response + ", address: " + remoteAddr + "}."); | |
return false; | |
} | |
final ReCaptchaImpl reCaptcha = new ReCaptchaImpl(); | |
reCaptcha.setPrivateKey(Properties.getProperty("recaptcha.private.key")); | |
final ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, challengeResponse); | |
if (reCaptchaResponse != null && reCaptchaResponse.isValid()) | |
return true; | |
logger.error(reCaptchaResponse.getErrorMessage()); | |
return false; | |
} catch (Exception e) { | |
logger.error(e.getMessage(), e); | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment