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 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>
to where to want it to display on the page.
- If you wish to show recaptcha widget on 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 post it to this URL.
Google returns JSON in the below format,
- {
- "success": true|false,
- "challenge_ts": timestamp,
- "hostname": string,
- "error-codes": [...]
- }
When success is true, it means the Captcha is verified, if it's false then user has not passed reCaptcha test, you can check error-codes for additional errors.
I’ve provided a sample implementation. Please check code below,
- [HttpPost]
- public ActionResult ABCD(FormCollection form) {
- if (string.IsNullOrWhiteSpace(form["g-recaptcha-response"])) {
-
- }
- ReCaptchaResponse reCaptchaResponse = VerifyCaptcha("xxxxSecret Keyxxxx", form["g-recaptcha-response"]);
- if (!reCaptchaResponse.success) {
-
-
- }..........
- }
-
- public static ReCaptchaResponse VerifyCaptcha(string secret, string response) {
- if (request != 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:
- var responseString = Response.Content.ReadAsStringAsync().Result;
- if (!string.IsNullOrWhiteSpace(responseString)) {
- ReCaptchaResponse response = JsonConvert.DeserializeObject < ReCaptchaResponse > (responseString);
- return response;
- } else
-
- }
- }
- else
-
- }
-
-
- 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
https://developers.google.com/recaptcha/intro
https://www.google.com/recaptcha
https://en.wikipedia.org/wiki/ReCAPTCHA