CAPTCHA stands for "Completely Automated Public Turing test to tell Computers and Humans Apart." It's a type of challenge-response test used on websites and online services to determine whether the user is human or a bot.
In this post, we will learn how to integrate CAPTCHA in an ASP.NET Core application, using Google reCAPTCHA v2 a popular and reliable.
Integrate Google reCAPTCHA in ASP.NET Core
Getting Started
Before dive into integration of Google reCAPTCHA, let's understand what is captcha, it's purpose and how it works.
What is a CAPTCHA?
CAPTCHA is a type of challenge-response test used in computing to verify that the user is a human and not an automated program (bot) by presenting tasks that are easy for humans to solve but difficult for computers. The term stands for Completely Automated Public Turing test to tell Computers and Humans Apart.
Google reCAPTCHA is a free service that helps protect your website from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart. We'll use reCAPTCHA v2 ("I'm not a robot") checkbox in this example.
Purpose of CAPTCHA
The purpose of CAPTCHA is to distinguish between human users and automated bots on websites or online services. It helps prevent automated software from performing actions that could be abusive or harmful, such as:
- Spamming forms or comment sections
- Creating fake accounts
- Scraping websites
- Buying up tickets or goods unfairly
- Logging into accounts by brute-force
- Generating fraudulent transactions
How CAPTCHA Works
- Challenge Generation: When you visit a website that uses CAPTCHA, the site generates a challenge—like distorted letters, an image puzzle, or a checkbox to click.
- User Interaction: You, as the user, respond to the challenge. For example, typing the letters you see, selecting images matching a prompt, or simply clicking “I’m not a robot.”
- Verification: The website’s backend system verifies your response.
- For text CAPTCHAs , it compares your input with the correct answer it generated.
- For image CAPTCHAs , it checks if the selected images match the target category.
- For “I’m not a robot” checkboxes (like Google’s reCAPTCHA), it analyzes your behavior before, during, and after the click (mouse movements, timing) to distinguish humans from bots.
- Decision:If your response matches the expected answer or behavior pattern, the system assumes you’re human and lets you proceed (e.g., submit a form). If it detects bot-like behavior or wrong answers, it blocks or challenges you again.
Integrate Google reCAPTCHA in ASP.NET Core
Integrating Google reCAPTCHA in an ASP.NET Core application involves these main steps:- Register your site with Google reCAPTCHA and get the Site Key and Secret Key.
- Add the reCAPTCHA widget to your form (client-side).
- Validate the user's response token on the server-side by calling Google’s verification API.
- ASP.NET Core 6.0 or later (steps are similar for 3.1/5.0)
- Basic MVC setup with Razor views
- Google account to register for reCAPTCHA
Register Your Site with Google
- Go to Google reCAPTCHA Admin Console
- Register a new site:
- Label: Your app name
- reCAPTCHA Type: reCAPTCHA v2 → "I'm not a robot" Checkbox
- Domains: e.g.,
localhost
,yourdomain.com
- Submit and get:
- Site key
- Secret key
Add Keys to appsettings.json
{
"GoogleReCaptcha": {
"SiteKey": "YOUR_SITE_KEY",
"SecretKey": "YOUR_SECRET_KEY"
}
}
Create a Model for reCAPTCHA Response
public class reCaptcha
{
public bool Success { get; set; }
public string Challenge_ts { get; set; }
public string Hostname { get; set; }
public List<string> ErrorCodes { get; set; }
}
Create a Service to Validate reCAPTCHA
public interface IReCaptchaService
{
Task<bool> IsReCaptchaPassed(string token);
}
public class ReCaptchaService : IReCaptchaService
{
private readonly IConfiguration _config;
private readonly IHttpClientFactory _httpClientFactory;
public ReCaptchaService(IConfiguration config, IHttpClientFactory httpClientFactory)
{
_config = config;
_httpClientFactory = httpClientFactory;
}
public async Task<bool> IsReCaptchaPassed(string token)
{
var secretKey = _config["GoogleReCaptcha:SecretKey"];
var httpClient = _httpClientFactory.CreateClient();
var response = await httpClient.PostAsync(
$"https://www.google.com/recaptcha/api/siteverify?secret={secretKey}&response={token}",
null
);
if (!response.IsSuccessStatusCode)
return false;
var jsonResponse = await response.Content.ReadAsStringAsync();
var captchaResult = JsonSerializer.Deserialize<reCaptcha>(jsonResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return captchaResult?.Success ?? false;
}
}
Register Services in Setup.cs
or Program.cs
builder.Services.AddHttpClient();
builder.Services.AddScoped<IReCaptchaService, ReCaptchaService>();
Create the Form in Your Razor View
<form method="post">
<!-- Your form fields here -->
<div class="g-recaptcha" data-sitekey="@Configuration["GoogleReCaptcha:SiteKey"]"></div>
<span asp-validation-for="ReCaptchaToken" class="text-danger"></span>
<button type="submit">Submit</button>
</form>
@section Scripts {
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
}
Update Your ViewModel
public class RegisterViewModel
{
// Your form fields (e.g., Name, Email, etc.)
[Required]
public string ReCaptchaToken { get; set; }
}
Validate reCAPTCHA in the Controller
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model, [FromServices] IReCaptchaService reCaptchaService)
{
if (!ModelState.IsValid)
return View(model);
var isCaptchaValid = await reCaptchaService.IsReCaptchaPassed(model.ReCaptchaToken);
if (!isCaptchaValid)
{
ModelState.AddModelError(string.Empty, "CAPTCHA validation failed.");
return View(model);
}
// Continue registration logic...
return RedirectToAction("Success");
}
Summary
Adding Google reCAPTCHA to your ASP.NET Core application is a crucial measure to safeguard your forms against bots and spam. This guide has helped you implement a secure and modern CAPTCHA solution with reliable server-side validation.
Thanks