Automated applications (bots, robots) can perform brute force attacks to your contact forms or registration pages. These attacks may cause a leakage in confidential information as well as service outage.
The crucial approach to prevent automated applications to mess up with your web forms is that using captcha verification. There are several third party services to implement captcha in your website. I will briefly explain how to use Google’s service called Google reCAPTCHA.
How to use Google reCAPTCHA?
- Sign up and create a new record
- It will give you a SITE KEY and SECRET KEY. You will use these values below
- Add this line before the closing </head> tag in HTML page:
<script src='https://www.google.com/recaptcha/api.js'></script>
- Add this line where you want the reCAPTCHA widget to appear (Make sure to replace YOUR-SITE-KEY with your own site key):
<div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY"></div>
- Once user clicks the submit button in your page, make this AJAX call in your JavaScript function (Make sure to replace YOUR-SECRET-KEY with your own secret ):
var captchaResult = grecaptcha.getResponse(); var googleCallResult; $.ajax({ type: "POST", url: "https://www.google.com/recaptcha/api/siteverify?secret=YOUR-SECRET-KEY&response=" + captchaResult, contentType: "application/json; charset=utf-8", dataType: "json", failure: function (response) { alert(response.d); }, success: function (response) { // if googleCallResult equals "true", captcha verification // is successful. It equals "false" if verification fails googleCallResult = response.success; } }).done(function () { // Do stuff with googleCallResult });
- That’s all! By using the variable “googleCallResult“, you can build your logic in your page. This variable will have “true” if the captcha verification is successful.
.
Call a function as soon as the user verifies captcha
- Add “data-callback” attribute to your div class (Make sure to replace YOUR-SITE-KEY with your own site key):
<div class="g-recaptcha" data-sitekey="YOUR-SITE-KEY" data-callback='captchaSuccessful'></div>
- Add your JavaScript function. This function will be called once user verify the captcha
function captchaSuccessful() { // Do stuff here }
.
More info about Google reCAPTCHA:
https://developers.google.com/recaptcha/intro
{
“success”: true|false,
“challenge_ts”: timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd’T’HH:mm:ssZZ)
“apk_package_name”: string, // the package name of the app where the reCAPTCHA was solved
“error-codes”: […] // optional
}