Add Captcha in your ASP.NET Core Website

Nowadays, if you have a publicly available form, you must have a captcha to stop bots from posting spammy data.

Add your site to the reCaptcha console

ReCaptcha is the most popular captcha service on the Internet. It’s offered for free by Google.

You must create an account and add your site to the admin console.

When you add your domain, make sure that you select the reCAPTCHA V2 option (I’m not a robot Checkbox).

Add site to Recaptcha Console

Don’t forget to copy the Site Key and the secret key in a notepad. We will need these two values later.

In the website settings you’ve added, you can set how difficult the captcha will be.

reCAPTCHA Level of Protection

Install a NuGet package that supports reCAPTCHA

I like to use Paul Miami’s reCAPTCHA library.

Install the NuGet Package:

Install-Package PaulMiami.AspNetCore.Mvc.Recaptcha

Configure reCAPTCHA in ASP.NET Core

  1. Add the site and secret key in the appsettings file:
    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "Recaptcha": {
        "SiteKey": "Your site key",
        "SecretKey": "Your secret key"
      }
    }
  2. Add the service to Program/Startup Class:
    services.AddRecaptcha(new RecaptchaOptions
    {
        SiteKey = builder.Configuration["Recaptcha:SiteKey"],
        SecretKey = builder.Configuration["Recaptcha:SecretKey"]
    });
  3. Import the tag helper. Add the following line in _ViewImports.cshtml file:
    @addTagHelper *, PaulMiami.AspNetCore.Mvc.Recaptcha
  4. Place the tag in the views or pages where you want to have reCaptcha:
    <recaptcha/>

    Add the jQuery libraries for validation and the Recaptcha script:

    <script src="~/lib/jquery/dist/jquery.js"></script>
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    <recaptcha-script/>
  5.  Decorate the actions with the attribute Validate Recaptcha:

You must decorate the page class instead of the method for Razor Pages.

Leave a Comment