19 Dec

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 thier reCAPTCHA API  to 2.0 . Now users can now 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 look as follows

recaptcha asp.net

recaptcha asp.net

Implementation

Now lets create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at 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 have 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

 <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.

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

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

<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 responce.

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. When ever user submit 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 above API url the secret and response parameters are required and where as 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.

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

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

public class CaptchaResponse
{
    [JsonProperty("success")]
    public bool 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.

[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

Source Code

You can download the source from the Github

19 thoughts on “Google reCAPTCHA in ASP.NET MVC

  1. The solution from Github does not run as written. On form submit the application errors because the view engine is looking for a ValidateCaptcha view in the Home folder which does not exist.

  2. Cannot apply operator ‘!’ to operand of type ‘string’ on !captchaResponse.Success

    Wouldn’t something like bool something = captchaResponse.Success == “true”; then if (something) {..} supposed to work better?

  3. Excuse me if i am localhost website in IDE not online website
    in google Register domain should i key localhost.com :D?

  4. Can you please help me on this, I am getting the below error.
    [{, “success”: false,, “error-codes”: [, “missing-input-secret”, ], }]

    Is my secret is wrong as part method call or what is the issue. if my secret is correct I think we will get “true” as success code.

    Thanks,
    Gajendra

  5. Venkat, great article! I found your article after searching a good bit. I am glad theres some help, but wish there was more information on using it with a log-in page in ASP MVC.

    1) Can you pen something around… how to combine repatcha with a login form.

    2) For e.g. what are the steps involved,
    3) and where is the hand-off happening, after recaptcha passes, how can I then have the login form become active.

    A sample would be great.

    thanks

  6. Hello, I’, sorry stepping through it, and not making sense on whats happening.

    Can you update your source, it doesn’t match the list here or have any documents on where to put the keys.

    I just see one location that says key value pair… whats is the format to put it inside the code, can you list “xxuyyx, sskjjd”??? what format and where all should i put the key please.

    • I finally got it to build :)) thanks, (the issue was with a shadow copy below might have come from github version).

      1) I was asking how do I integrate with my custom login in form, i.e. after signup as well, I mean the steps, can you explain sequentially (before after I authenticate)
      2) I see numbers not a check box – how can I get the check box like you have rather than numbers?
      3) How can I apply this not just for registration/sign-up but also login form. And where in the code would you recommend I put this, after what steps

      “Cannot create/shadow copy ‘Recaptcha.Web’ when that file already exists.

      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

      Exception Details: System.IO.FileLoadException: Cannot create/shadow copy ‘Recaptcha.Web’ when that file already exists.

      Source Error:

      An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

      Assembly Load Trace: The following information can be helpful to determine why the assembly ‘Recaptcha.Web’ could not be loaded.

      === Pre-bind state information ===
      LOG: DisplayName = Recaptcha.Web
      (Partial)

      • Hi,

        Step 1: You can generate racaptcha keys from the following link
        https://www.google.com/recaptcha/admin

        Step 2: After that, place the div tag under the form and add the required scripts to the form

        Step3: Once the form is submitted, first validate google reCaptcha and then you can authenticate the user

        At first, reCaptcha checkbox is displayed, if it fails then its asks for the numbers not the checkbox again.

        • Ok thanks so much. That was exactly what I was looking for, now its clear.

          So, to confirm, the reCaptcha call happens twice, or is both on client side for image and server side for validation correct? or am I serving the client side image/box as well.

          One more question, can you please expand on how to add SimpleMembership on an existing project, and update your github sample.

  7. My friend your site is very very slow!!

    BTW – this is the easy stuff, please show how to do membership securely and easily in ASP MVC project.

    Include a sample on extending the user/employee for other trans/actions uses like expenses table or holiday table etc.

    Danka

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>