Recaptcha.Verify.Net 2.3.0

dotnet add package Recaptcha.Verify.Net --version 2.3.0
NuGet\Install-Package Recaptcha.Verify.Net -Version 2.3.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Recaptcha.Verify.Net" Version="2.3.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Recaptcha.Verify.Net --version 2.3.0
#r "nuget: Recaptcha.Verify.Net, 2.3.0"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Recaptcha.Verify.Net as a Cake Addin
#addin nuget:?package=Recaptcha.Verify.Net&version=2.3.0

// Install Recaptcha.Verify.Net as a Cake Tool
#tool nuget:?package=Recaptcha.Verify.Net&version=2.3.0

Recaptcha.Verify.Net

NuGet Build

Library for server-side verification of Google reCAPTCHA v2/v3 response token for ASP.NET.

Recaptcha.Verify.Net starting from version 2.0.0 supports the following platforms and any target that supports .NET Standard from 2.0:

  • .NET Standard 2.0
  • .NET Standard 2.1
  • .NET Framework 4.6.2
  • .NET 6
  • .NET 7

Table of Contents

Installation

Package can be installed using Visual Studio UI (Tools > NuGet Package Manager > Manage NuGet Packages for Solution and search for "Recaptcha.Verify.Net").

Also latest version of package can be installed using Package Manager Console:

PM> Install-Package Recaptcha.Verify.Net

Verifying reCAPTCHA response

  1. Add secret key in appsettings.json file.
{
  "Recaptcha": {
    "SecretKey": "<recaptcha secret key>",
    "ScoreThreshold": 0.5
  }
}
  1. Configure service in Startup.cs.
public void ConfigureServices(IServiceCollection services)
{
    services.AddRecaptcha(Configuration.GetSection("Recaptcha"));
    //...
}
  1. Use service in controller to verify captcha answer and check response action and score for V3.
[ApiController]
[Route("api/[controller]")]
public class LoginController : Controller
{
    private const string _loginAction = "login";
    
    private readonly ILogger _logger;
    private readonly IRecaptchaService _recaptchaService;

    public LoginController(ILoggerFactory loggerFactory, IRecaptchaService recaptchaService)
    {
        _logger = loggerFactory.CreateLogger<LoginController>();
        _recaptchaService = recaptchaService;
    }

    [HttpPost]
    public async Task<IActionResult> Login([FromBody] Credentials credentials, CancellationToken cancellationToken)
    {
        var checkResult = await _recaptchaService.VerifyAndCheckAsync(
            credentials.RecaptchaToken,
            _loginAction,
            cancellationToken);
        
        if (!checkResult.Success)
        {
            if (!checkResult.Response.Success)
            {
                // Handle unsuccessful verification response
                _logger.LogError("Recaptcha error: {errorCodes}", JsonConvert.SerializeObject(checkResult.Response.ErrorCodes));
            }
            
            if (!checkResult.ScoreSatisfies)
            {
                // Handle score less than specified threshold for v3
            }
            
            // Unsuccessful verification and check
            return BadRequest();
        }
        
        // Process login
        
        return Ok();
    }
}

Using attribute for verifying reCAPTCHA response

  1. Specify in appsettings.json name of parameter for a way in which reCAPTCHA response token is passed.
{
  "Recaptcha": {
    ...
    "AttributeOptions": {
      "ResponseTokenNameInHeader": "RecaptchaTokenInHeader", // If token is passed in header
      "ResponseTokenNameInQuery": "RecaptchaTokenInQuery", // If token is passed in query
      "ResponseTokenNameInForm": "RecaptchaTokenInForm" // If token is passed in form
    }
  }
}

Or set in Startup GetResponseTokenFromActionArguments or GetResponseTokenFromExecutingContext delegate that points how to get token from parsed data.

services.AddRecaptcha(Configuration.GetSection("Recaptcha"),
    // Specify how to get token from parsed arguments for using in RecaptchaAttribute
    o => o.AttributeOptions.GetResponseTokenFromActionArguments =
        d =>
        { 
            if (d.TryGetValue("credentials", out var credentials))
            {
                return ((BaseRecaptchaCredentials)credentials).RecaptchaToken;
            }
            return null;
        });

Credentials model used in example has base class with property containing token.

public class BaseRecaptchaCredentials
{
    public string RecaptchaToken { get; set; }
}
public class Credentials : BaseRecaptchaCredentials
{
    public string Login { get; set; }
    public string Password { get; set; }
}
  1. Add Recaptcha attribute in controller to verify captcha answer and check response action and score for V3.
[Recaptcha("login")]
[HttpPost("Login")]
public async Task<IActionResult> Login([FromBody] Credentials credentials, CancellationToken cancellationToken)
{
    // Process login
    return Ok();
}

Directly passing score threshold

Score threshold in appsettings.json is optional and value could be passed directly into VerifyAndCheckAsync function.

var scoreThreshold = 0.5f;
var checkResult = await _recaptchaService.VerifyAndCheckAsync(
    credentials.RecaptchaToken,
    _loginAction,
    scoreThreshold);

Using score threshold map

Based on the score, you can take variable actions in the context of your site instead of blocking traffic to better protect your site. Score thresholds specified for actions allow you to achieve adaptive risk analysis and protection based on the context of the action.

  1. Specify ActionsScoreThresholds in appsettings.json. If specified ScoreThreshold value will be used as default score threshold for actions that are not in map.
{
  "Recaptcha": {
    "SecretKey": "<recaptcha secret key>",
    "ScoreThreshold": 0.5,
    "ActionsScoreThresholds": {
      "login": 0.75,
      "test": 0.9
    }
  }
}
  1. Call VerifyAndCheckAsync function
// Response will be checked with score threshold equal to 0.75
var checkResultLogin  = await _recaptchaService.VerifyAndCheckAsync(credentials.RecaptchaToken, "login");

// Response will be checked with score threshold equal to 0.9
var checkResultTest   = await _recaptchaService.VerifyAndCheckAsync(credentials.RecaptchaToken, "test");

// Response will be checked with score threshold equal to 0.5
var checkResultSignUp = await _recaptchaService.VerifyAndCheckAsync(credentials.RecaptchaToken, "signup");

Verifying reCAPTCHA response without checking action and score

If checking of verification response needs to be completed separately then you can use VerifyAsync instead of VerifyAndCheckAsync.

var response = await _recaptchaService.VerifyAsync(credentials.RecaptchaToken);

Handling exceptions

Library can produce following exceptions Exception | Description --- | --- EmptyActionException | This exception is thrown when the action passed in function is empty. EmptyCaptchaAnswerException | This exception is thrown when captcha answer passed in function is empty. HttpRequestException | This exception is thrown when http request failed. Stores Refit.ApiException as inner exception. MinScoreNotSpecifiedException | This exception is thrown when minimal score was not specified and request had score value (used V3 reCAPTCHA). SecretKeyNotSpecifiedException | This exception is thrown when secret key was not specified in options or request params. UnknownErrorKeyException | This exception is thrown when verification response error key is unknown.

All of these exceptions are inherited from RecaptchaServiceException.

Examples

Examples could be found in library repository:

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.3.0 5,606 8/30/2023
2.2.0 1,615 6/20/2023
2.1.0 1,391 4/2/2023
2.0.4 3,264 8/3/2022
2.0.2 438 7/11/2022
2.0.1 544 5/15/2022
2.0.0 1,431 2/20/2022
1.2.0 569 2/6/2022
1.1.1 527 2/1/2022
1.1.0 559 2/1/2022
1.0.2 2,603 5/19/2021
1.0.1 745 3/28/2021
1.0.0 567 3/26/2021