GithubHelp home page GithubHelp logo

hcaptcha's Introduction

hCaptcha for .NET

This project is not official by hCaptcha.com.

HCaptcha HCaptcha.AspNetCore
NuGet NuGet NuGet
License GitHub GitHub
GitHub Build NETCore

Dependencies

Refit

The HCaptcha.AspNetCore project contains the interface IHCaptchaApi for use with Refit. Refit is an open source project for type-safe handling of REST endpoints, as provided by hCaptcha.com.

If you can't or don't want to use Refit, you can create your own implementation of IHCaptchaApi or see usage of hCaptcha without this project.

Usage with ASP.NET Core

1) Options

The configuration is represented via the HCaptchaOptions class. Some values are setwith the current default values of hCaptcha.com. SiteKey and Secret must be inserted.

The easiest way is to use the .NET Core Configuration via the appsettings.json

"HCaptcha": {
   "SiteKey": "", // Overwrite them with yours
   "Secret": "" // Overwrite them with yours
}

and the registration via AddHCaptcha, which is part of HCaptcha.AspNetCore.

public void ConfigureServices(IServiceCollection services)
{
   // HCaptcha
   services.AddHCaptcha(Configuration.GetSection("HCaptcha"));
   ...

2) Model Binder Registration

Currently the ASP.NET core library offers an automatism for the integration of HCaptcha. For this purpose a ModelBinder is used, which is applied as soon as the type HCaptchaVerifyResponse is part of the action.

You have to register the Model Binder.

public void ConfigureServices(IServiceCollection services)
{
    // HCaptcha
    services.AddHCaptcha(Configuration.GetSection("HCaptcha"));

    // Mvc
    services.AddControllersWithViews(mvcOptions =>
        // add model binder
        mvcOptions.AddHCaptchaModelBinder());
}

And your Action:

public class HomeController : Controller
{
    [HttpGet, Route("")]
    public IActionResult Index()
    {
        return View(new IndexViewModel());
    }

    [HttpPost, Route("")]
    public IActionResult Index(HCaptchaVerifyResponse hCaptcha)
    {
        return View(new IndexViewModel(hCaptcha));
    }
}

Alternatively, the ModelBinder can be specified directly in the action.

public class HomeController : Controller
{
    [HttpPost, Route("")]
    public IActionResult Index([ModelBinder(BinderType = typeof(HCaptchaModelBinder))]HCaptchaVerifyResponse hCaptcha)
    {
        return View(new IndexViewModel(hCaptcha));
    }
}

It would also be possible to solve the whole automatism via a ServiceFilter instead of via the ModelBinder.

Sample

An ASP.NET Core 6.0 example can be found in the sample directory. You only have to add the SiteKey and the Secret to appsettings.json.

Sample Preview

Use hCaptcha without this project

If you don't want to use this project to request the hCaptcha.com API, you can do so with standard .NET functionality.

HttpClient

HttpClient is intended to be instantiated once per application!
See HttpClient documentation.

private static readonly HttpClient HttpClient = new HttpClient();
public async Task Verify(string secret, string token, string remoteIp)
{
    try
    {
        // create post data
        List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("secret", secret),
            new KeyValuePair<string, string>("response", token),
            new KeyValuePair<string, string>("remoteip", remoteIp)
        };

        // request api
        HttpResponseMessage response = await HttpClient.PostAsync(
            // hCaptcha wants URL-encoded POST
            "https://hcaptcha.com/siteverify", new FormUrlEncodedContent(postData));

        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();

        Console.WriteLine(responseBody);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"Message : { e.Message}");
    }
}

HttpClientFactory

Register HttpClient

// named registration
services.AddHttpClient("hCaptcha", c =>
{
   c.BaseAddress = new Uri("https://hcaptcha.com/");
});

Use IHttpClientFactory in your class

public class YourServiceClass
{
    private readonly IHttpClientFactory _clientFactory;

    public YourServiceClass(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<HttpResponseMessage> Verify(string secret, string token, string remoteIp)
    {
        // HttpClient client = _clientFactory.CreateClient(); 
        //    if you dont have a named service registration
        HttpClient client = _clientFactory.CreateClient("hCaptcha");

        // create post data
        List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("secret", secret),
            new KeyValuePair<string, string>("response", token),
            new KeyValuePair<string, string>("remoteip", remoteIp)
        };

        // request api
        return await client.PostAsync(
            // base url is given in IHttpClientFactory service registration
            // hCaptcha wants URL-encoded POST
            "/siteverify", new FormUrlEncodedContent(postData));
    }

Donation

Please donate - if possible - to necessary institutions of your choice such as child cancer aid, children's hospices etc. Thanks!

License

MIT License

hcaptcha's People

Contributors

benjaminabt avatar alex-451 avatar

Stargazers

 avatar Felix Strauß avatar Yure Pereira avatar  avatar  avatar Media Explorer avatar Saeed Darandi avatar n0tbr1dg3 avatar Josh Fraser avatar Kadir İlhan avatar Conan the Dev avatar demn avatar Lucas Benninger avatar  avatar  avatar  avatar Elyor Latipov avatar  avatar Kyle avatar Alexis Chân Gridel avatar David De Smet avatar Sagilio avatar Kot C avatar  avatar Jamie Howarth avatar

Watchers

James Cloos avatar  avatar  avatar

hcaptcha's Issues

Add option to configure HttpClientHandler

This library should support named HttpClients. This allows the use of, for example, a proxy server.

As this library is using Refit, this would be done like so, to use the named client "Default":

clientBuilder.ConfigureHttpMessageHandlerBuilder(handlerBuilder => handlerBuilder.Name = "Default")

I tried to fork this and add it myself using another parameter for AddHCaptcha: https://github.com/Matti-Koopa/hcaptcha/blob/master/src/HCaptcha.AspNetCore/HCaptchaExtensions.cs so that you can do something like this:

services.AddHCaptcha(captchaSection, clientBuilder =>
    clientBuilder.ConfigureHttpMessageHandlerBuilder(handlerBuilder => handlerBuilder.Name = "Default"));

Sadly, I couldn't get this to work locally as Refit always complained that IHCaptchaApi "doesn't look like a Refit interface" (seems to be this issue).

Maybe you could get it to work somehow? An alternative would be to just get rid of the Refit dependency alltogether. It seems overkill for just a single endpoint anyway.

"The Hostname field is required." Error

If the captcha is not solved it returns a weird Error:
The Hostname field is required.

Do you know where this error is coming from and what causes it?

I assume the error is set by the library because it only exists after the form post request has been sent

captchaOptions:
image

Latest Nuget package is broken

Hi there! I'm trying to implement this as an action filter in an ASP.NET MVC project (thus I can just add [HCaptchaValidator] to my actions - neat!)
However, your latest build appears to be broken, as it's not generating the Refit internal class (I've worked on Refit quite a bit myself, see screenshot):
Screenshot of JetBrains dotPeek showing an "empty" Refit-generated namespace, excluding the PreserveAttribute that's always present

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.