Introduction
ReCAPTCHA is a CAPTCHA-like system designed to establish that a computer user is human (normally in order to protect websites from bots) and, at the same time, ReCAPTCHA lets you embed a CAPTCHA in your web pages in order to protect them against spam and other types of automated abuse. Recaptcha is owned by Google.
This article shows how to integrate reCaptcha version 2.0 into an ASP.Net MVC website.
Prerequisites
Visual Studio, a web browser, and a valid Google account. (The example uses Visual Studio 2015 Update 3, .Net Framework 4.5, and Firefox web browser 50.1.0 ).
Prior knowledge of HTML, .Net, and ASP.Net MVC is required.
Step 1. Get the API Key And Secret.
Login to your Google account. Then go here.
If it shows “Invisible? Incredible. Coming soon. The Invisible reCAPTCHA. “
Click continue and do not sign up.
You will be redirected to here then click on Get reCAPTCHA.
Now, the Admin page loads. It shows a list of sites you’ve registered for reCaptcha.
Enter your details in the Register a new site section. Add a label to identify the site and add a list of domains. Also, remember to add localhost if you intend to test it on your local machine ( PC ).
Click register, and you will be provided with your site key and secret key.
Step 2. Add Recaptcha To Your View.
Automatically render the reCAPTCHA widget.
Open the view page on which you intend to show the recaptcha. In the head section of the page, add the script.
<script src="https://www.google.com/recaptcha/api.js"></script>
Then add,
<div class="g-recaptcha" data-sitekey="xxxxxxxxx"></div>
It is where you want it to display on the page.
If you wish to show the recaptcha widget at a JavaScript event.
Specify your onload callback function. This function will get called when all the dependencies have loaded.
<script type="text/javascript">
var onloadCallback = function() {
alert("reCaptcha is ready !!!");
};
</script>
Insert the Javascript resource, setting the onload parameter to the name of your onload callback function and the render parameter to explicit.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
When your callback is executed, you can call the grecaptcha.render method from the Javascript API.
Note. Your onload callback function must be defined before the reCAPTCHA API loads. To ensure there are no race conditions,
- Order your scripts with the callback first, and then reCAPTCHA
- Use the async and defer parameters in the script tags.
Note. Ensure you add the reCaptcha widget inside the form tag.
Step 3. Verify Recatcha Response.
Now go to the controller and the action that will handle the submit event of the view.
In the action, we will need to add FormCollection in the parameter as g-recaptcha-response cannot be made into a parameter as .Net doesn’t allow – (hyphen/dash) in the variable name.
We then verify the response by posting it to this URL.
Google returns JSON in the below format.
{
"success": true|false,
"challenge_ts": "timestamp", // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": "string", // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
When success is true, it means the Captcha is verified, if it's false then the user has not passed reCaptcha test, and you can check error codes for additional errors.
I’ve provided a sample implementation. Please check the code below.
[HttpPost]
public ActionResult ABCD(FormCollection form)
{
if (string.IsNullOrWhiteSpace(form["g-recaptcha-response"]))
{
// Throw error as required
}
ReCaptchaResponse reCaptchaResponse = VerifyCaptcha("xxxxSecret Keyxxxx", form["g-recaptcha-response"]);
if (!reCaptchaResponse.success)
{
// Throw error as required
// You can also log errors returned from Google in reCaptchaResponse.error_codes
}
// Additional logic
}
// Function ... you can create it in a different class
public static ReCaptchaResponse VerifyCaptcha(string secret, string response)
{
if (response != null)
{
using (System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient())
{
var values = new Dictionary<string, string>
{
{ "secret", secret },
{ "response", response }
};
var content = new System.Net.Http.FormUrlEncodedContent(values);
var response = hc.PostAsync("https://www.google.com/recaptcha/api/siteverify", content).Result;
var responseString = response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrWhiteSpace(responseString))
{
ReCaptchaResponse captchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(responseString);
return captchaResponse;
}
else
{
// Throw error as required
}
}
}
else
{
// Throw error as required
}
return null; // Ensure to return a valid response or handle errors as needed
}
// You can use http://json2csharp.com/ to create C# classes from JSON
// Note: "error-codes" is an invalid name for a variable in C# so we use "_" and then add JsonProperty to it
public class ReCaptchaResponse
{
public bool success { get; set; }
public string challenge_ts { get; set; }
public string hostname { get; set; }
[JsonProperty(PropertyName = "error-codes")]
public List<string> error_codes { get; set; }
}
Error code |
Description |
missing-input-secret |
The secret parameter is missing. |
invalid-input-secret |
The secret parameter is invalid or malformed. |
missing-input-response |
The response parameter is missing. |
invalid-input-response |
The response parameter is invalid or malformed. |
Future
Google soon plans on releasing Invisible reCAPTCHA. It’s now available as Beta.
References