Click here to Skip to main content
15,179,830 members
Articles / Web Development / HTML
Technical Blog
Posted 9 Feb 2015

Tagged as

Stats

54.3K views
22 bookmarked

Google reCAPTCHA in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.69/5 (12 votes)
9 Feb 2015CPOL2 min read
Google reCAPTCHA in ASP.NET MVC

Here, I will explain about how to use Google reCAPTCHA in ASP.NET MVC. What is reCAPTCHA?

reCAPTCHA protects the websites you love from spam and abuse. Google has updated their reCAPTCHA API to 2.0 . Now, users can attest they are human without having to solve a CAPTCHA. Instead with just a single click, they’ll confirm they are not a robot and it is called as “No CAPTCHA reCAPTCHA“. This is how new reCAPTCHA looks:

recaptcha asp.net

recaptcha asp.net

Implementation

Now let's create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at the top of the page and follow the below steps to create an application.

reCAPTCHA - Register application in google recaptcha

reCAPTCHA – Register application in google recaptcha

Once you are done with registration, the following keys will be generated:

reCAPTCHA  keys

reCAPTCHA keys

Site key: is used to display the widget in your page or code.

Secret key: can be used as communication between your site and Google to verify the user response whether the reCAPTCHA is valid or not.

Now the next is display the reCAPTCHA widget in your site.

Displaying Widget

We can render the widget in two ways as:

  1. Automatically render the widget
  2. Explicitly render the widget

For this example, we will use Automatically render the widget in your page.

First, load the script reference:

HTML
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Now, you need generate a DIV element with class name as g-recaptcha and your site key in the data-site key attribute in your webpage to generate reCAPTCHA.

HTML
<div class="g-recaptcha" data-sitekey="your_site_key"></div>

Now, implement the above code in Home/Index.cshtml view page.

HTML
<div class="row">
    <div class="col-md-12">
        <form action="/home/validatecaptcha" method="POST">
            <div class="g-recaptcha" 
            data-sitekey="6LfiS_8SAAAAABvF6ixcyP5MtsevE5RZ9dTorUWr"></div>
            <br />
            <input type="submit" value="Submit">
        </form>
    </div>
  
</div>
@section scripts{
   <script src="https://www.google.com/recaptcha/api.js" async defer></script>
}

Next step is verify the user response.

Verify User Response

Once reCAPTCHA is generated and solved by a end user, a field with g-recaptcha-response will be populated in the html. Whenever user submits the form on your site, you can POST the parameter g-recaptcha-response to verify the user response. The following API URL is used to verify the user response.

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

In the above API URL, the secret and response parameters are required and whereas remoteip is optional. Here, secret represents the Secret Key that was generated in the key pair and the repsonse is the g-recaptcha-response that was submitted during the form post. The following is the API JSON response object that we get once the response is submitted.

C#
{
  "success": true|false,
  "error-codes": [...]   // optional
}

We will create a response class to verify the user response.

C#
public class CaptchaResponse
{
    [JsonProperty("success")]
    public string Success { get; set; }

    [JsonProperty("error-codes")]
    public List<string> ErrorCodes { get; set; }
}

Now, we will create a POST method in Index action in the Home controller to verify the user response.

C#
[HttpPost]
public ActionResult ValidateCaptcha()
{
    var response = Request["g-recaptcha-response"];
    //secret that was generated in key value pair
    const string secret = "YOUR KEY VALUE PAIR";

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

    var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

    //when response is false check for the error message
    if (!captchaResponse.Success)
    {
        if (captchaResponse.ErrorCodes.Count <= 0) return View();

        var error = captchaResponse.ErrorCodes[0].ToLower();
        switch (error)
        {
            case ("missing-input-secret"):
                ViewBag.Message = "The secret parameter is missing.";
                break;
            case ("invalid-input-secret"):
                ViewBag.Message = "The secret parameter is invalid or malformed.";
                break;

            case ("missing-input-response"):
                ViewBag.Message = "The response parameter is missing.";
                break;
            case ("invalid-input-response"):
                ViewBag.Message = "The response parameter is invalid or malformed.";
                break;

            default:
                ViewBag.Message = "Error occured. Please try again";
                break;
        }
    }
    else
    {
        ViewBag.Message = "Valid";
    }

    return View();
}

reCAPTCHA  output

The post Google reCAPTCHA in ASP.NET MVC appeared first on Venkat Baggu Blog.

This article was originally posted at http://venkatbaggu.com/google-recaptcha-asp-net-mvc

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

madan535
Software Developer (Senior) eBiz Solutions http://venkatbaggu.com/
India India
No Biography provided

Comments and Discussions

 
Suggestionadd call back method. Pin
Member 1347845621-Mar-18 12:28
MemberMember 1347845621-Mar-18 12:28 
Questionin CaptchaResponse class, success should be a bool Pin
Member 1109139526-Apr-15 3:40
MemberMember 1109139526-Apr-15 3:40 
GeneralThank you baba Pin
Member 1109139526-Apr-15 2:32
MemberMember 1109139526-Apr-15 2:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.