Site Map Contact Us Home
E-mail Newsletter
Subscribe to get informed about
Clever Components news.

Your Name:
Your Email:
 
SUBSCRIBE
 
Previous Newsletters
 




Products Articles Downloads Order Support
Customer Portal      

Using Google Invisible reCAPTCHA in the ASP.NET Login Page

Google reCAPTCHA in ASP.NET

Introduction

Google reCAPTCHA protects you against spam and other types of automated abuse. It is used to stop spam on a website and verify whether a user is a human.

This article provides an example of implementing invisible reCAPTCHA on an ASP.NET Login page.

There are three possible types of invoking invisible reCAPTCHA: automatically bind the challenge to the Login button, programmatically bind the challenge to the Login button, and programmatically invoke the challenge.

In this document, the challenge is invoked programmatically after pressing the Login ASP.NET button on the form.

After resolving reCAPTCHA on the client side, you need to validate the user‘s response by submitting the g-recaptcha-response information to the Google reCAPTCHA service.

Let’s consider all the steps of adding the Google Invisible reCAPTCHA to the ASP.NET Login page.

Download on GitHub

 

Getting an API Key Pair

Before using reCAPTCHA, you need to sign up for an API key pair for your site using the http://www.google.com/recaptcha/admin link.

If you already have a google account, you can log in using it. Otherwise, register a new account. The key pair consists of a Site Key and a Secret Key. The Site Key is used on the client side. This key is public and available for everybody. The Secret Key is sent along with the g-recaptcha-response field to the Google service while validating the user’s reCAPTCHA input.

To avoid hardcoding, let us keep the key pair information in the Web.config file of your website:

<!--  web.config  -->

<appSettings>
   <add key="CaptchaSiteKey" value="6Ld0KE8UAAAAAGCLnVoKBo-moA_Lz1bMc8PN23-3"/>
   <add key="CaptchaSecret" value="6Ld…"/>
</appSettings>

The code that extracts and substitutes the key information in the ASP.NET Login page is located in the the Login.aspx.cs file and demonstrated below.

// Login.aspx.cs

public partial class Account_Login : Page
{

   public string CaptchaSiteKey
   {
      get
      {
         return System.Configuration.ConfigurationManager.AppSettings["CaptchaSiteKey"];
      }
   }

}

The content of the Login.aspx page:

<!-- Login.aspx -->

<div class="g-recaptcha"
   data-sitekey="<%:CaptchaSiteKey%>"
   data-callback="DoLogin"
   data-size="invisible">
</div>

 

Integrating the code in the Login page

First of all, you need to add a link to the Google reCAPTCHA API on your web page. After that, specify the necessary API downloading options, such as an asynchronous downloading, the executing mode, and the language option. Note that it is also important to place this link before any references to the reCAPTCHA members within the web page:

<!-- Login.aspx -->

<script src='https://www.google.com/recaptcha/api.js?hl=ru' async defer></script>

Next, you need to create a div with data-size='invisible' and the data-sitekey information and put it next to your Login ASP:Button. If you use the Bootstrap css styles, you can customize your Login button as you need here.

<!-- Login.aspx -->

<div class="g-recaptcha"
   data-sitekey="<%:CaptchaSiteKey%>"
   data-callback="DoLogin"
   data-size="invisible">
</div>
<asp:Button ID="btnLogIn" runat="server" OnClick="LogIn" Text="Войти" CssClass="btn btn-primary" />

The issue that needs to be resolved is to invoke the reCAPTCHA function after the standard ASP.NET user input validation and before the Login form’s submit. One possible solution is to replace the Login button’s OnClick event handler and call the original event handler manually when the reCAPTCHA validation completes. The function below looks for the Login button element, replaces the OnClick event handler with the new one, and saves the original event handler to the btnLoginEvent variable.

You can call the DoLoad function at the end of the web page. In this case you can be sure that the script will be executed when the HTML document has been fully parsed.

The code that does the work is implemented in the DoValidate function. This function calls the standard ASP.NET client’s Page_ClientValidate input validation function. If there are no input errors, the Google reCAPTCHA code is invoked the grecaptcha.execute() method.

The third code part initiating the login process is represented by the DoLogin function. The name of this function is specified using the data-callback attribute of the reCAPTCHA div. The reCAPTCHA API executes this function immediately after a user has successfully passed the reCAPTCHA validation process. This is a place, where you can restore the original Login’s OnClick event handler and invoke it.

The code below demonstrates an implementation of the mentioned functions and the btnLoginEvent variable. The Google reCAPTCHA API link is declared above this code:

<!-- Login.aspx -->

<script src='https://www.google.com/recaptcha/api.js?hl=ru' async defer></script>
<script>
var btnLoginEvent = null;

function DoLogin() {
   var btn = document.getElementById("<%:btnLogIn.ClientID%>");
   btn.onclick = btnLoginEvent;
   btn.click();
}

function DoValidate(event) {
   event.preventDefault();
   if (Page_ClientValidate()) {
      grecaptcha.execute();
   }
}

function DoLoad() {
   var btn = document.getElementById("<%:btnLogIn.ClientID%>");
   btnLoginEvent = btn.onclick;
   btn.onclick = DoValidate;
}
</script>

The code that calls the DoLoad function at the end of the web page:

<!-- Login.aspx -->


   <script>
      DoLoad();
   </script>
</asp:Content>

 

Server Side Validation

When the form is generated in a browser, the reCAPTCHA API adds a hidden form field called the “g-recaptcha-response”. To validate the form, you need to send an AJAX request to the Google service, and provide the content of this field along with your secret key. This service returns a reply in the JSON format with the “true” value if the response and the key are valid. Otherwise it returns the “false” value.

The code below sends a validation request and deserializes the Google service response:

// ReCaptcha.cs

public class ReCaptcha
{
   public static bool Validate(string privateKey, string reCaptchaResponse)
   {
      var client = new System.Net.WebClient();

      var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", privateKey, reCaptchaResponse));

      var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptcha>(googleReply);

      return (captchaResponse.Success.ToLower() == "true");
   }

   [JsonProperty("success")]
   public string Success
   {
      get { return m_Success; }
      set { m_Success = value; }
   }

   private string m_Success;
   [JsonProperty("error-codes")]
   public List<string> ErrorCodes
   {
      get { return m_ErrorCodes; }
      set { m_ErrorCodes = value; }
   }

   private List<string> m_ErrorCodes;
}

You can call the ReCaptcha.Validate method in your LogIn event handler of the Login ASP.NET button. Below you can find a sample implementation with the LogIn method. The code uses the standard ASP.NET UserManager, and the IdentityHelper class. You can use the necessary implementation according to your task.

// Login.aspx.cs

protected void LogIn(object sender, EventArgs e)
{
   if (!ReCaptcha.Validate(CaptchaSecret, Request.Form["g-recaptcha-response"]))
   {
      FailureText.Text = "reCAPTCHA Error";
      ErrorMessage.Visible = true;
   }
   else if (IsValid)
   {
      // Validate the user password
      var manager = new UserManager();
      ApplicationUser user = manager.Find(UserName.Text, Password.Text);
      if (user != null)
      {
         IdentityHelper.SignIn(manager, user, RememberMe.Checked);
         IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
      }
      else
      {
         FailureText.Text = "Login failed";
         ErrorMessage.Visible = true;
      }
   }
}

You can download a project illustrating this approach using the link below:

Download on GitHub

Ask a Question

 

Sergey Shirokov
Clever Components team
www.clevercomponents.com

    Copyright © 2000-2024