Add Captcha in your ASP.NET Core Website

Nowadays, if you have a form that is publicly available, you must have a captcha in order to stop bots to post 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 in a notepad the Site Key and the secret key.  We will need these two values later.

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

reCAPTCHA Level of Protection

Install a NuGet package that supports reCAPTCHA

I personally 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 in 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:

For Razor Pages, you must decorate the page class instead of the method.

Leave a Comment