Implementing CAPTCHA in ASP.NET Core Web Application

CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a security mechanism used to differentiate between human users and automated bots. In this tutorial, we'll learn how to integrate Google reCAPTCHA with an ASP.NET Core web application to prevent spam and abuse.

Step 1. Obtain reCAPTCHA Keys

First, you need to obtain reCAPTCHA keys from the Google reCAPTCHA website. Sign in with your Google account, register a new site, and obtain the site key and secret key.

Step 2. Add reCAPTCHA to the HTML Form

In your HTML form, include the reCAPTCHA widget provided by Google. Replace "YOUR_SITE_KEY" with your actual reCAPTCHA site key.

<!-- HTML Page -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample Form with CAPTCHA</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <h2>Sample Form with CAPTCHA</h2>
    <form action="/SubmitForm" method="post">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" required>
        </div>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

Step 3. Create Controller Action for Form Submission

In your ASP.NET Core controller, create an action method to handle the form submission. Use the HttpClient to verify the reCAPTCHA response.

// Controller Action for Form Submission
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;

public class FormController : Controller
{
    [HttpPost]
    public async Task<IActionResult> SubmitForm(FormModel model, string captchaResponse)
    {
        if (await VerifyCaptcha(captchaResponse))
        {
            // CAPTCHA verification successful
            // Process form submission
            return RedirectToAction("Success");
        }
        else
        {
            // CAPTCHA verification failed
            ModelState.AddModelError("", "CAPTCHA verification failed. Please try again.");
            return View(model);
        }
    }

    private async Task<bool> VerifyCaptcha(string captchaResponse)
    {
        var secretKey = "YOUR_SECRET_KEY";
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={captchaResponse}");
        if (response.IsSuccessStatusCode)
        {
            var jsonResponse = await response.Content.ReadAsStringAsync();
            // Deserialize JSON response and check 'success' property
            // Return true if CAPTCHA is valid, false otherwise
            return true; // Placeholder
        }
        return false;
    }
}

Step 4. Model Class

Create a model class to represent the form data.

// Model Class
public class FormModel
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Step 5. Create a Success View

Create a success view to display a confirmation message after the form submission is successful.

<!-- Success View -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Submission Success</title>
</head>
<body>
    <h2>Form Submitted Successfully!</h2>
    <p>Thank you for your submission.</p>
</body>
</html>

Here's how you can deserialize the JSON response from Google reCAPTCHA and check the 'success' property to determine if the CAPTCHA is valid or not:

using Newtonsoft.Json;
using System;

private async Task<bool> VerifyCaptcha(string captchaResponse)
{
    var secretKey = "YOUR_SECRET_KEY";
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync($"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={captchaResponse}");
    if (response.IsSuccessStatusCode)
    {
        var jsonResponse = await response.Content.ReadAsStringAsync();
        var captchaResult = JsonConvert.DeserializeObject<CaptchaResponse>(jsonResponse);
        return captchaResult.Success;
    }
    return false;
}

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

In this code snippet

  • We use Newtonsoft.Json package to deserialize the JSON response.
  • We define a CaptchaResponse class with a Success property corresponding to the 'success' field in the JSON response.
  • We deserialize the JSON response into an instance of the CaptchaResponse class and access the Success property to determine if the CAPTCHA is valid.

Conclusion

Implementing CAPTCHA in your ASP.NET Core web application adds an additional layer of security to protect against automated bots and spam. By integrating Google reCAPTCHA, you can effectively verify the authenticity of user interactions and prevent malicious activities.