Overview
In this Bolg, I will explore the integration of Google reCAPTCHA V2 with ASP.NET applications and how to customize the reCAPTCHA widget.
What is reCAPTCHA
Google reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
This is a free service from Google that helps protect websites from spam and abuse that restricts the automated input sent by a system and allows only input from a real human.

Prerequisites
Here, I will create a sample ASP.NET website to integrate Google reCAPTCHA. So, the following are the prerequisites for this article.
- We should have a Google account where we can register our sites for reCAPTCHA
- Visual Studio
Understanding the Properties of RecaptchaControl
The RecaptchaControl provides many properties as a simple control but the following are some of the common properties:
- PublicKey: This is a mandatory property that validates the user request on the client-side. This is unique key is provided by Google for the website concerning the website domain.
- PrivateKey: This is a mandatory property that validates the user request at the server-side with the Google server. This is a unique secret key provided by Google for the website domain basically for communicating between our server and the Google server.
- ErrorMessage: This is an optional property that sets an error message when the user enters an invalid CAPTCHA.
- AllowMultipleInstances: This is an optional property that decides the number of CAPTCHA code generations at a time. By default, it is false. If it is set to true then two CAPTCHA codes are generated for a single request.
- Theme: This is used to set the background color for the CAPTCHA control.
Site Registration for reCAPTCHA
So, first, we need to register our site/domain with Google ReCaptcha v2 API to get the site key and secret key. So now, I am going to register our domains (www.yourdomainname.com) where I will use these keys for reCAPTCHA integration. Click here for domain registration.
Note
We can mention multiple domains along with localhost. After clicking on the Register button, the following screen will appear reCAPTCHA Site key and Secret key.
We can mention multiple domains along with localhost. After clicking on the Register button, the following screen will appear reCAPTCHA Site key and Secret key.
Now, we have all the things ready to integrate the reCAPTCHA on websites.
For this article, I am going to create an empty website with the name reCAPTCHA and after that, I will add a new page named Default.aspx.
reCAPTCHA Auto Rendering
Automatic Rendering Widget
- <body>
- <form id="form1" runat="server">
- <div class="g-recaptcha" data-sitekey="6Lfn8DoUAAAAAEuzI65jbXXNaewCS9BwO_XXXXXXXX"></div>
- </form>
- <script src='https://www.google.com/recaptcha/api.js'></script>
- </body>
This is the easiest way to rendering a reCaptcha on a web page. In the above code snippet, we can see that there is a div element having two attributes class and data-sitekey and both these attributes are mandatory.
- g-recaptcha is mandatory to make render recaptcha widget, we can not use own class name.
- data-sitekey is the key which is provided by Google reCAPTCHA for the domains which are mentioned at the time of reCAPTCHA v2 registration.
Google reCAPTCHA API Parameters
Following are the reCAPTCHA API Parameters and all these parameters are optional.
- calback - The name of your callback function to be executed once all the dependencies have loaded.
- render - Whether to render the widget explicitly. Defaults to onload, which will render the widget in the first g-recaptcha tag it finds.
- hl - Forces the widget to render in a specific language. Auto-detects the user's language if unspecified.
reCAPTCHA Integration With Website
Rendering reCAPTCHA Explicitly
Step 1
Create an empty ASP.NET website and a new page Default.aspx and put the following code snippet inside the body tag.
Default.aspx
- <div id="ReCaptchContainer"></div>
- <label id="lblMessage" runat="server" clientidmode="static"></label>
- <br />
- <button type="button" >Submit</button>
In the above HTML code snippet, I have taken a div tag where recaptha widget will be rendered and there is a label to display validation message for recaptcha on button click.
Step 2
Refer the reCaptcha API script on the page. For this article, I am putting this script at the bottom of the body.
- <!--Refere reCaptcha API-->
- <script src="https://www.google.com/recaptcha/api.js" async defer></script>
In this article, we are going to render the widget explicitly so we need to add onload and render parameters with reCaptcha API script.
Here, the onload parameter's value is renderRecaptcha which is a JavaScript function that renders the reCaptcha widget and the render value is explicit which show that render the widget explicitly by calling the function renderRecaptcha.
- <!--Refere reCaptcha API-->
- <script src="https://www.google.com/recaptcha/api.js?onload=renderRecaptcha&render=explicit" async defer></script>
Now, add the follwing script for reCAPTCHA render and it's callback functions.
- <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
- <script type="text/javascript">
- var your_site_key = '<%= ConfigurationManager.AppSettings["SiteKey"]%>';
- var renderRecaptcha = function () {
- grecaptcha.render('ReCaptchContainer', {
- 'sitekey': your_site_key,
- 'callback': reCaptchaCallback,
- theme: 'light', //light or dark
- type: 'image',// image or audio
- size: 'normal'//normal or compact
- });
- };
- var reCaptchaCallback = function (response) {
- if (response !== '') {
- jQuery('#lblMessage').css('color', 'green').html('Success');
- }
- };
- jQuery('button[type="button"]').click(function(e) {
- var message = 'Please checck the checkbox';
- if (typeof (grecaptcha) != 'undefined') {
- var response = grecaptcha.getResponse();
- (response.length === 0) ? (message = 'Captcha verification failed') : (message = 'Success!');
- }
- jQuery('#lblMessage').html(message);
- jQuery('#lblMessage').css('color', (message.toLowerCase() == 'success!') ? "green" : "red");
- });
- </script>
Step 4
Let us run the page to test the reCAPTCHA functionality.
Step 5 Server Side Validation
For server-side validation, we need to call reCaptcha siteverify API along with parameters secretkey and response (recaptcha response after form submit).
Folliwing are the API URL.
https://www.google.com/recaptcha/api/siteverify?secret=<secret-key>&response=<captcha-response>
- public bool IsReCaptchValid()
- {
- var result = false;
- var captchaResponse = Request.Form["g-recaptcha-response"];
- var secretKey = ConfigurationManager.AppSettings["SecretKey"];
- var apiUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
- var requestUri = string.Format(apiUrl, secretKey, captchaResponse);
- var request = (HttpWebRequest)WebRequest.Create(requestUri);
- using(WebResponse response = request.GetResponse())
- {
- using (StreamReader stream = new StreamReader(response.GetResponseStream()))
- {
- JObject jResponse = JObject.Parse(stream.ReadToEnd());
- var isSuccess = jResponse.Value<bool>("success");
- result = (isSuccess) ? true : false;
- }
- }
- return result;
- }
Now, call this method on button click to validate the reCaptcha input.
- protected void btnTry_Click(object sender, EventArgs e)
- {
- lblMessage.InnerHtml = (IsReCaptchValid())
- ? "<span style='color:green'>Captcha verification success</span>"
- : "<span style='color:red'>Captcha verification failed</span>";
- }
Now, execute the program to test the server-side validation.
In the above JSON result object, "success: True" indicates that reCAPTCHA challenges validation success.
If anyone wants to see some sites where google reCAPTHCA is used
- Google reCAPTCHA Demo By Google
https://www.google.com/recaptcha/api2/demo - C# Corner
http://www.c-sharpcorner.com/register
Summary
In this article, we learned what Google reCAPTCHA is, how to register our site for reCAPTHCA, how to integrate the reCAPTCHA widget with the web page, how to validate reCAPTCHA challenges on the client-side as well as server-side in an ASP.NET application.

..Really i am impressed from this post....the person who create this post it was a great human.. thanks for shared this with us. 2captcha login
ReplyDelete