Skip to content

Latest commit

 

History

History
159 lines (113 loc) · 5.86 KB

README.md

File metadata and controls

159 lines (113 loc) · 5.86 KB

ASP.NET Core reCAPTCHA

A Google reCAPTCHA service for ASP.NET Core. Keep bots away from submitting forms or other actions in just a few steps.

The service supports V2 and V3 and comes with tag helpers that make it easy to add challenges to your forms. Also, backend validation is made easy and requires only the use of an attribute in your controllers or actions that should get validated.

Build Status Build Status License NuGet GitHub Release

Installation

Install via NuGet using:

PM> Install-Package Griesoft.AspNetCore.ReCaptcha

Quickstart

Prequisites

You will need an API key pair which can be acquired by signing up here. For assistance or other questions regarding that topic, refer to Google's guide.

After sign-up, you should have a Site key and a Secret key. You will need those to configure the service in your app.

Configuration

Settings

Open your appsettings.json and add the following lines:

"RecaptchaSettings": {
    "SiteKey": "<Your site key goes here>",
    "SecretKey": "<Your secret key goes here>"
}

Important: The SiteKey will be exposed to the public, so make sure you don't accidentally swap it with the SecretKey.

Service Registration

Register this service by calling the AddRecaptchaService() method which is an extension method of IServiceCollection. For example:

.NET 6
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRecaptchaService();
Prior to .NET 6
public void ConfigureServices(IServiceCollection services)
{
    services.AddRecaptchaService();
}

Adding a reCAPTCHA element to your view

First, import the tag helpers. Open your _ViewImports.cshtml file and add the following lines:

@using Griesoft.AspNetCore.ReCaptcha
@addTagHelper *, Griesoft.AspNetCore.ReCaptcha

Next, you need to add the <recaptcha-script> to every view you intend to use the reCAPTCHA. That will render the API script. Preferably you would add this somewhere close to the bottom of your body element.

Now you may add a reCAPTCHA challenge to your view where ever you need it. Using the <recaptcha /> tag in your form will render a reCAPTCHA V2 checkbox inside it.

For invisible reCAPTCHA use:

<button re-invisible form-id="yourFormId">Submit</button>

For reCAPTCHA V3 use:

<recaptcha-v3 form-id="yourFormId" action="submit">Submit</recaptcha-v3>

Adding backend validation to an action

Validation is done by decorating your controller or action with [ValidateRecaptcha].

For example:

using Griesoft.AspNetCore.ReCaptcha;
using Microsoft.AspNetCore.Mvc;

namespace ReCaptcha.Sample.Controllers
{
    public class ExampleController : Controller
    {
        [ValidateRecaptcha]
        public IActionResult FormSubmit(SomeModel model)
        {
            // Will hit the next line only if validation was successful
            return View("FormSubmitSuccessView");
        }
    }
}

Now each incoming request to that action will be validated for a valid reCAPTCHA token.

The default behavior for invalid tokens is a 404 (BadRequest) response. But this behavior is configurable, and you may also instead request the validation result as an argument to your action.

This can be achieved like this:

[ValidateRecaptcha(ValidationFailedAction = ValidationFailedAction.ContinueRequest)]
public IActionResult FormSubmit(SomeModel model, ValidationResponse recaptchaResponse)
{
    if (!recaptchaResponse.Success)
    {
        return BadRequest();
    }

    return View("FormSubmitSuccessView");
}

In case you are validating a reCAPTCHA V3 token, make sure you also add an action name to your validator.

For example:

[ValidateRecaptcha(Action = "submit")]
public IActionResult FormSubmit(SomeModel model)
{
    return View("FormSubmitSuccessView");
}

Options & Customization

There are global defaults that you may modify on your application startup. Also, the appearance and position of V2 tags may be modified. Either globally or each tag individually.

All options from the official reCAPTCHA docs are available to you in this package.

Proxy Server

If your environment requires to use forward proxy server, this can be done by specifying two additional parameters in the configuration file

"RecaptchaSettings": {
    "UseProxy": true,
    "ProxyAddress": "http://10.1.2.3:80"
}

The address should contain port and protocol, as required by the System.Net.WebProxy class.

Detailed Documentation

Is on it's way...

Contributing

Contributing is heavily encouraged. 💪 The best way of doing so is by first starting a discussion about new features or improvements you would like to make. Or, in case of a bug, report it first by creating a new issue. From there, you may volunteer to fix it if you like. 😄