How to integrate Google’s "I’m not a robot" reCAPTCHA in ASP.NET
In this article you will learn how to use Google’s new reCAPTCHA “I’m not a robot” in ASP.NET
applications. Google’s reCAPTCHA is a free service which protects your website
from spam, abuse and bots. Google has updated their CAPTCHA API version to
reCAPTCHA API 2.0
The new version of reCAPTCHA is very secure with attractive layout.
With the help of new version users can attest as they are human without
inputting blurry numbers or solving problems. With just a single click Google’s
reCPATCH will confirm you are not a robot. This new version also called as No CAPTCHA reCPATCHA.
The first step to integrate the Google’s reCAPTCHA is to
register your website domain. Go to the below website link and click on Get reCAPTCHA button.
Input your application name in label field, your website
domain name under Domains field and click on ‘Register’ button.
Note: If you want
to test reCAPTCHA in your local machine, just add localhost in Domains field.
Upon successful registration you will get Site Key and
Secret Key as shown below.
Site Key: It is
used to display reCAPTCHA widget in your site.
Secret Key: It is
used to verify whether the user response to reCAPTCHA is valid or not.
Display reCAPTCHA
The next is display the reCAPTCHA widget on your site. We
will see this step practically by having a login screen and verify reCAPTCHA before user login.
Copy and paste the below script reference before closing
</head> tag.
[pre class="brush:html; toolbar: false;" title=""]
<script src='https://www.google.com/recaptcha/api.js'></script>
[/pre]
Copy and paste the below snippet before closing the </form> tag where you want to appear the reCAPTCHA widget.
[pre class="brush:html; toolbar: false;" title=""]
<div class="g-recaptcha" data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP">
</div>
[/pre]
Here is the sample login from with reCAPTCHA widget in my .aspx page
[pre class="brush:html; toolbar: false;" title="simple login form with reCAPTCHA"]
<form id="form1" runat="server">
<div>
<h2><u>Dotnet 4 Techies</u></h2>
<h3>Login Now</h3>
</div>
<div>
<table>
<tr>
<td>Username:</td>
<td>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</div>
<div class="g-recaptcha" data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP"></div>
<br />
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
</form>
[/pre]
Verify reCAPTCHA
[pre class="brush:html; toolbar: false;" title=""]
<script src='https://www.google.com/recaptcha/api.js'></script>
[/pre]
Copy and paste the below snippet before closing the </form> tag where you want to appear the reCAPTCHA widget.
[pre class="brush:html; toolbar: false;" title=""]
<div class="g-recaptcha" data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP">
</div>
[/pre]
Here is the sample login from with reCAPTCHA widget in my .aspx page
[pre class="brush:html; toolbar: false;" title="simple login form with reCAPTCHA"]
<form id="form1" runat="server">
<div>
<h2><u>Dotnet 4 Techies</u></h2>
<h3>Login Now</h3>
</div>
<div>
<table>
<tr>
<td>Username:</td>
<td>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
</td>
</tr>
</table>
</div>
<div class="g-recaptcha" data-sitekey="6LcqFg8UAAAAADUK7coDHgoeTXEdJ9JQICdCyVcP"></div>
<br />
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
</form>
[/pre]
Verify reCAPTCHA
When you submit a form which includes the reCAPTCHA, you
will get a response in a variable called g-recaptcha-response.
To confirm whether user has been verified with reCAPTCHA, you need to send a GET call to below URL by including your secret key, response from g-recaptcha-response variable and user IP address.
To confirm whether user has been verified with reCAPTCHA, you need to send a GET call to below URL by including your secret key, response from g-recaptcha-response variable and user IP address.
Here is the code on how to verify the user response to reCAPTCHA upon clicking login button.
[pre class="brush:c-sharp; toolbar: false;" title="code to verify reCAPTCHA upon login"]
protected void btnLogin_Click(object sender, EventArgs e)
{
string errorMessage = string.Empty;
bool isValidCaptcha = ValidateReCaptcha(ref errorMessage);
if (isValidCaptcha)
{
//connect to your db and verfiy login details
}
else
{
//show an errorMessage and YOU ARE A ROBOT
}
}
public bool ValidateReCaptcha(ref string errorMessage)
{
var gresponse = Request["g-recaptcha-response"];
string secret = "6LcqFg8UAAAAAO_FQuzRejzk9fa004PO86sy8d0";
string ipAddress = GetIpAddress();
var client = new WebClient();
string url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}
&response={1}&remoteip={2}", secret, gresponse, ipAddress);
var response = client.DownloadString(url);
var captchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(response);
if (captchaResponse.Success)
{
return true;
}
else
{
var error = captchaResponse.ErrorCodes[0].ToLower();
switch (error)
{
case ("missing-input-secret"):
errorMessage = "The secret key parameter is missing.";
break;
case ("invalid-input-secret"):
errorMessage = "The given secret key parameter is invalid.";
break;
case ("missing-input-response"):
errorMessage = "The g-recaptcha-response parameter is missing.";
break;
case ("invalid-input-response"):
errorMessage = "The given g-recaptcha-response parameter is invalid.";
break;
default:
errorMessage = "reCAPTCHA Error. Please try again!";
break;
}
return false;
}
}
string GetIpAddress()
{
var ipAddress = string.Empty;
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
else if (!string.IsNullOrEmpty(Request.UserHostAddress))
{
ipAddress = Request.UserHostAddress;
}
return ipAddress;
}
public class ReCaptchaResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("error-codes")]
public List<string> ErrorCodes { get; set; }
}
[/pre]
[pre class="brush:c-sharp; toolbar: false;" title="code to verify reCAPTCHA upon login"]
protected void btnLogin_Click(object sender, EventArgs e)
{
string errorMessage = string.Empty;
bool isValidCaptcha = ValidateReCaptcha(ref errorMessage);
if (isValidCaptcha)
{
//connect to your db and verfiy login details
}
else
{
//show an errorMessage and YOU ARE A ROBOT
}
}
public bool ValidateReCaptcha(ref string errorMessage)
{
var gresponse = Request["g-recaptcha-response"];
string secret = "6LcqFg8UAAAAAO_FQuzRejzk9fa004PO86sy8d0";
string ipAddress = GetIpAddress();
var client = new WebClient();
string url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}
&response={1}&remoteip={2}", secret, gresponse, ipAddress);
var response = client.DownloadString(url);
var captchaResponse = JsonConvert.DeserializeObject<ReCaptchaResponse>(response);
if (captchaResponse.Success)
{
return true;
}
else
{
var error = captchaResponse.ErrorCodes[0].ToLower();
switch (error)
{
case ("missing-input-secret"):
errorMessage = "The secret key parameter is missing.";
break;
case ("invalid-input-secret"):
errorMessage = "The given secret key parameter is invalid.";
break;
case ("missing-input-response"):
errorMessage = "The g-recaptcha-response parameter is missing.";
break;
case ("invalid-input-response"):
errorMessage = "The given g-recaptcha-response parameter is invalid.";
break;
default:
errorMessage = "reCAPTCHA Error. Please try again!";
break;
}
return false;
}
}
string GetIpAddress()
{
var ipAddress = string.Empty;
if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
else if (!string.IsNullOrEmpty(Request.UserHostAddress))
{
ipAddress = Request.UserHostAddress;
}
return ipAddress;
}
public class ReCaptchaResponse
{
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("error-codes")]
public List<string> ErrorCodes { get; set; }
}
[/pre]
That’s it. Hope you understand the Google’s reCAPTCHA
integration process. The given implementation is not only specific to ASP.NET,
the same you can convert into any other language app as per your need.
If you
have any questions please discuss then using comments section below. Thanks…
Very good Content Thanks for Sharing it
ReplyDeleteDotNet Training in Chennai
Hi.
ReplyDeleteI have used this code but it keeps crashing on the when getting the URL ValidateReCaptcha(ref string errorMessage) method with "Input string was not in a correct format" error message. Is there something i am missing?
{"The operation has timed out"} in this line var response = client.DownloadString(url);
ReplyDeletestring url = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}
ReplyDelete&response={1}&remoteip={2}", secret, gresponse, ipAddress);
cannot use local variabel 'respose', pleasee help me.. how to handle it ...
What is the: JsonConvert. I got error on this line
ReplyDeleteYou have to download Newtonsoft.Json.dll from https://www.newtonsoft.com/json and add an using in the login page (or you can use a nuget package)
ReplyDeleteShare your google page on additional social media channels: If you are not already, you should take full advantage of as many of the popular (and appropriate) social media channels as you possibly can.reviews on google
ReplyDeleteI have got the timeout issue, when deploy in the live server,
ReplyDeleteworking fine in the local domain.
please suggest solution.
Your firewall is probably blocking out going request to google.com, can you visit the url in a browser on the production machine?
DeleteCan I get the Asp.net core code for this implementation?? Thanks
ReplyDeleteThis website and I conceive this internet site is really informative ! Keep on putting up! anti captcha
ReplyDelete