Coder Social home page Coder Social logo

timothymeadows / recaptcha.aspnetcore Goto Github PK

View Code? Open in Web Editor NEW
143.0 10.0 50.0 1.25 MB

Google reCAPTCHA v2/v3 for .NET Core 3.x

License: MIT License

C# 86.77% HTML 11.53% CSS 1.46% JavaScript 0.25%
recaptcha asp-net-core asp-net-mvc core2 google-recaptcha aspnetcore netframework core3 core31 dotnet

recaptcha.aspnetcore's Introduction

reCAPTCHA.AspNetCore

License: MIT nuget

Google reCAPTCHA for .NET Core 3.x. The older .NET Core 2.x version can be found here.

Note: There have been changes to this libraries structure between versions 2, and 3. If you still wish to use version 2 it's been frozen at version 2.2.5 on nuget.

Install

From a command prompt

dotnet add package reCAPTCHA.AspNetCore
Install-Package reCAPTCHA.AspNetCore

You can also search for package via your nuget ui / website:

https://www.nuget.org/packages/reCAPTCHA.AspNetCore/

Requirements

You must first have a secret key and a site key in order to use the reCAPTCHA service. This package supports v2 and v3 api keys. You can read more about reCAPTCHA v2, and v3 as well as sign up for free here: https://www.google.com/recaptcha/intro/

Configure

Choose how you want to configure the storage of your RecaptchaSettings. This contains your site key, and site secret so it's recommended to use secrets.json with Azure Key Vault (or similar setup). However you can also just add the section to your appconfig.json file.

appconfig.json

Add the follow entry to the file make sure to paste in your secret key and site key followed by setting the correct version to v2 or v3 depending on your key type:

"RecaptchaSettings": {
    "SecretKey": "paste secret key here",
    "SiteKey": "paste site key here"
  } 

secrets.json

Right click on your project file and goto Manage Secrets.

This will open secrets.json. Add the follow entry to the file make sure to paste in your secret key and site key followed by setting the correct version to v2 or v3 depending on your key type:

"RecaptchaSettings": {
    "SecretKey": "paste secret key here",
    "SiteKey": "paste site key here"
  } 

Note: This will also require you to have a setup such as Azure Key Vault (or similar setup) when running in production.

Content Security Policy

If you use a content security policy you can specify the values for script-src, and frame-src using the below example. Note that you should also make sure the Site option used for those who suffer from censorship matches the values you are using. The default value for Site is www.google.com.

"RecaptchaSettings": {
    "SecretKey": "paste secret key here",
    "SiteKey": "paste site key here",
    "ContentSecurityPolicy": "https://www.google.com/recaptcha/"
  } 

This is an example for those that have to use recaptcha.net which would also have to change the site value:

"RecaptchaSettings": {
    "SecretKey": "paste secret key here",
    "SiteKey": "paste site key here",
    "Site": "www.recaptcha.net",
    "ContentSecurityPolicy": "https://www.recaptcha.net/recaptcha/"
  } 

Versions

These are the currently supported versions. Below is also the list of class names for T when using Html.Recaptcha<T>

Examples

Open Startup.cs and add the following code as shown below to your ConfigureServices method:

// Add recaptcha and pass recaptcha configuration section
services.AddRecaptcha(Configuration.GetSection("RecaptchaSettings"));

// Or configure recaptcha via options
services.AddRecaptcha(options =>
{
    options.SecretKey = "Your secret key";
    options.SiteKey = "Your site key";
});

Usage

In order to prevent having to copy and paste your site key all over your view files (a nightmare to update later). You can inject your settings from the Startup method by adding the following code to top of your view file:

@inject IOptions<RecaptchaSettings> RecaptchaSettings

You can then freely include the Recaptcha script inside of forms you wish to validate later in your controller (supports multiple forms).

@using (Html.BeginForm("SomeMethod", "SomeController")) {
  @(Html.Recaptcha<RecaptchaV2Checkbox>(RecaptchaSettings?.Value))
}

If you wish to trigger a JavaScript function on callback you can pass a method name to the Html helper.

@using (Html.BeginForm("SomeMethod", "SomeController")) {
  @(Html.Recaptcha<RecaptchaV2Checkbox>(RecaptchaSettings?.Value, new RecaptchaV2Checkbox { successCallback = "methodName" }))
}
<script>
  function methodName() {
    alert('caw caw caw!');
  }
</script>

You can specify the language in the optional model.

@(Html.Recaptcha(RecaptchaSettings?.Value, new RecaptchaV2Checkbox
{
    Language = System.Globalization.CultureInfo.CurrentCulture.Name.Substring(0,2)
}))

You may find that you need to add a reference to Microsoft.Extensions.Options before you can use IOptions.

@using Microsoft.Extensions.Options
@using reCAPTCHA.AspNetCore

You can see a tested example of usage in the Contact.cshtml view. However you will need to configure it with your key information before running yourself. You should also take note of the allowed domains security policy in the Google Recaptcha docs.

Validation

You can validate the recaptcha attempts using the ValidateRecaptchaAttribute on your HttpPost method:

[HttpPost]
[ValidateRecaptcha]
public async Task<IActionResult> SomeMethod(SomeModel model)
{
  return View(model);
}

You can also specify a minimum score you wish to accept when a success occurs:

[HttpPost]
[ValidateRecaptcha(0.5)]
public async Task<IActionResult> SomeMethod(SomeModel model)
{
  return View(model);
}

You can see a tested example of usage in the HomeController.cs controller. However you will need to configure it with your key information before running yourself. You should also take note of the allowed domains security policy in the Google Recaptcha docs.

Recaptcha.net

Users who suffer from censorship concerns can now bypass the libraries default of www.google.com to www.recaptcha.net, or a proxy of there choosing using the following optional setting in appsettings.json.

"RecaptchaSettings": {
    "Site": "www.recaptcha.net",
    "SecretKey": "paste secret key here",
    "SiteKey": "paste site key here"
  }

Unique Issues / Solutions

recaptcha.aspnetcore's People

Contributors

aahventures avatar atrejoe avatar brunobritodev avatar carlin-q-scott avatar daviddesloovere avatar kingzfate avatar mo-esmp avatar p-m-j avatar stackedbitz avatar stulzq avatar timothymeadows avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

recaptcha.aspnetcore's Issues

Customize model error messages

Model error message is a hard coded string:

context.ModelState.AddModelError("Recaptcha", "There was an error validating the google recaptcha response. Please try again, or contact the site owner.");

It would be nice if this message can be customized. The workaround that I use now is:

 if (ModelState.ContainsKey("Recaptcha") && ModelState["Recaptcha"].Errors.Any())
            {
                ModelState.Remove("Recaptcha");
                ModelState.AddModelError("Recaptcha", "Bevis at du ikke er en robot ved å klikke i avmerkingsboksen 'Jeg er ikke en robot'");
            }

jQuery validation conflict?

Thanks again @TimothyMeadows for all of your work on this! It looks like we may have a new problem.

  • With 2.2.1 and 2.2.2 all is well with the included test application here using both "v2" and "v2-invis".
  • If I uses a .net core 2.2 app with Razor Pages / "v2" and "v2-invis" and copy and paste your fom form the test app here, everything works fine.
  • If I uses a .net core 2.2 app with Razor Pages / "v2" and a form that uses jQuery validaton / tag helpers everything is fine.
  • If I uses a .net core 2.2 app with Razor Pages / "v2-invis" and a form that uses jQuery validaton / tag helpers everything NOT fine.
  • I didn't try this on the MVC app.

In one app the jQuery validation doesn't work at all and on another app it seems the form doesn't get posted at all and there are errors on the console saying that recaptcha has already been rendered

recaptcha__en.js:519 Uncaught Error: reCAPTCHA has already been rendered in this element
at Object.Fd (recaptcha__en.js:519)
at _5a5ca599_9550_4e83_b887_d45f8c348a10 (contact:185)
at $p (recaptcha__en.js:507)
at iG (recaptcha__en.js:508)
at recaptcha__en.js:521
at recaptcha__en.js:540
AAuE7mDuI1pqB7h1LyRUm04SML-HpWIjXkqEuv0worO3aw:1 Failed to load resource: the server responded with a status of 404 ()
AAuE7mDuI1pqB7h1LyRUm04SML-HpWIjXkqEuv0worO3aw:1 Failed to load resource: the server responded with a status of 404 ()
AAuE7mDuI1pqB7h1LyRUm04SML-HpWIjXkqEuv0worO3aw:1 Failed to load resource: the server responded with a status of 404 ()

Pre-release for the callback support

Hi. Would it be possible to have a nugget release/pre-release to get the newly introduced callback support? If not, when can we expect the next nugget release?

Does not work

Hi im trying to implement it but getting

Severity	Code	Description	Project	File	Line	Suppression State
Error	CS0246	The type or namespace name 'ValidateRecaptcha' could not be found (are you missing a using directive or an assembly reference?)	SSS	D:\Private\Projects\c#\=WWW=\SSS\SSS\Controllers\usersController.cs	151	Active

No matter what this is always the outcome.. :(

Proxy Support

Currently using on a .net core 2.2 project (running under windows). There appears to be no way to use this project via a proxy?

I believe under 2.0 the "internet options" proxy was automatically defined in the HttpClient. I guess this changed in 2.1 along with the inclusion of the HttpClientFactory?

Thanks in advance,
Mike

No service for type 'reCAPTCHA.AspNetCore.RecaptchaSettings'

Environment: Net Core 3.1. VisualStudio 2019, reCAPTCHA.AspNetCore 3.0.3 installed via NuGet, using reCaptcha v2 Tickbox.

I followed reCAPTCHA.AspNetCore.Example and made solution with just small adaptation.
When opening the view with Html.Recaptcha and @Inject RecaptchaSettings RecaptchaSettings I get the error message below.
If I copy the solution from GitHub which includes reCAPTCHA.AspNetCore.Example, reCAPTCHA.AspNetCore.Tests and reCAPTCHA.AspNetCore projects, this error is not present.

InvalidOperationException: No service for type 'reCAPTCHA.AspNetCore.RecaptchaSettings' has been registered.

Test case: Click Contacts in navbar
WebApplication23.zip

Error:
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.AspNetCore.Mvc.Razor.RazorPagePropertyActivator+<>c__DisplayClass8_0.b__1(ViewContext context)
Microsoft.Extensions.Internal.PropertyActivator.Activate(object instance, TContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorPagePropertyActivator.Activate(object page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorPageActivator.Activate(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Support for Razor Pages

As it stands, [ValidateRecaptcha] cannot be added to a Razor Page's OnPost or OnPostAsync method.

Is there any other way to verify the captcha response that isn't included in the readme?

Invisible ReCaptcha

Hello,

Do you have an example of using the invisible version of ReCaptcha?

Thanks

Add domain setting of the Google Captcha to the options

Thank you for sharing this practical project. My project is using it. I submitted a pull request to you a few days ago and you merged it. Now I found a small problem during the use, I want to discuss it with you.

I am in China. Google’s domain www.google.com is blocked by the Chinese government’s firewall. For most Chinese, they don’t have the ability to use VPN to penetrate this firewall. So they won’t be able to use the Google Captcha service properly. But Google additionally provides a domain to use the Google Captcha service. So I would like to suggest adding the Domain settings to the option. I have implemented it for use in my project: https://github.com/stulzq/reCAPTCHA.AspNetCore/blob/unicorn/reCAPTCHA.AspNetCore/RecaptchaService.cs#L52 . If you allow, I can submit a pull request.

Additional domain description: https://developers.google.com/recaptcha/docs/faq

image

v2-invis not working

This looks like a really well done project. Thank you!
Everything works perfectly with "v2".
When using "v2-invis" with the test project or my own project (with v2-invis keys), the submit button does not display. Actually, noting below

@Html.Recaptcha(RecaptchaSettings?.Value)

is rendered.

I see this on the console.

Uncaught Error: reCAPTCHA placeholder element must be an element or id
at Object.Fd [as render] (recaptcha__en.js:517)
at _8092d0ab_3436_48f8_802d_0d776994c3d1 (Contact:71)
at $p (recaptcha__en.js:507)
at iG (recaptcha__en.js:508)
at recaptcha__en.js:521
at recaptcha__en.js:540

Thanks! Maybe I am missing something.....

recaptcha v3

grecaptcha is always undefined. is inialization of recatcha api must go before checking grecaptcha in templates?

Implementation for Blazor (Server-Side)

Hi Timothy!

It's great what you have accomplished so far with this middleware.

For people who doesn't work with MVC apps do you have any workaround for Blazor apps?

I'm kinda struggling on this part (idk what to do on the razor page).

@using (Html.BeginForm("SomeMethod", "SomeController")) { @(Html.Recaptcha<RecaptchaV2Checkbox>(RecaptchaSettings?.Value)) }

Thanks in advance!

Not complete readme

Hello, and big thanks for your package, I really like it!
Could you add something to your readme?
<script src="https://www.google.com/recaptcha/api.js" async defer></script> - developer also must include this to his layout or view
And to add this @inject IOptions<RecaptchaSettings> RecaptchaSettings to his view he also must add using directive before, like @using Microsoft.Extensions.Options;

Translate error messages?

I'm using this in an application which has multilanguage support. Is there a way to translate or localize the error messages?

There was an error validating the google recaptcha response. Please try again, or contact the site owner.

false antiforgery exception

when testing and the captcha hostname is set to local host it throws on lione 34 of RecaptchaServices.cs because e.g. localhost != localhost:12345
looks like code should test against request.Host.Host.ToLower()

Error in Example

When running the sample web application an exception is thrown

An unhandled exception occurred while processing the request.
InvalidOperationException: No service for type 'reCAPTCHA.AspNetCore.RecaptchaSettings' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)

InvalidOperationException: No service for type 'reCAPTCHA.AspNetCore.RecaptchaSettings' has been registered.

Unable to activate The following constructors are ambiguous

`System.InvalidOperationException: Unable to activate type 'reCAPTCHA.AspNetCore.RecaptchaService'. The following constructors are ambiguous:
Void .ctor(reCAPTCHA.AspNetCore.RecaptchaSettings)
Void .ctor(Microsoft.Extensions.Options.IOptions`1[reCAPTCHA.AspNetCore.RecaptchaSettings])
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.<>c__DisplayClass7_0.<GetCallSite>b__0(Type type)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(Type serviceType, CallSiteChain callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at reCAPTCHA.AspNetCore.Attributes.ValidateRecaptchaAttribute.CreateInstance(IServiceProvider services)
   at Microsoft.AspNetCore.Mvc.Filters.DefaultFilterProvider.ProvideFilter(FilterProviderContext context, FilterItem filterItem)
   at Microsoft.AspNetCore.Mvc.Filters.DefaultFilterProvider.OnProvidersExecuting(FilterProviderContext context)
   at Microsoft.AspNetCore.Mvc.Filters.FilterFactory.CreateUncachedFiltersCore(IFilterProvider[] filterProviders, ActionContext actionContext, List`1 filterItems)
   at Microsoft.AspNetCore.Mvc.Filters.FilterFactory.GetAllFilters(IFilterProvider[] filterProviders, ActionContext actionContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerCache.GetCachedResult(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvokerProvider.OnProvidersExecuting(ActionInvokerProviderContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionInvokerFactory.CreateInvoker(ActionContext actionContext)
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointFactory.<>c__DisplayClass7_0.<CreateRequestDelegate>b__0(HttpContext context)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
--- End of stack trace from previous location where exception was thrown ---
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)`

Unhandled exception while using reCAPTCHA.AspNetCore v3

Installed version: 3.0.0
Project type: netcoreapp3.1

ArgumentNullException: Value cannot be null. (Parameter 'objectToConvert')

reCAPTCHA.AspNetCore.Templates.RecaptchaV3HiddenInputBase+ToStringInstanceHelper.ToStringWithCulture(object objectToConvert)
reCAPTCHA.AspNetCore.Templates.RecaptchaV3HiddenInput.TransformText()
reCAPTCHA.AspNetCore.RecaptchaHelper.Recaptcha(IHtmlHelper helper, RecaptchaSettings settings, T model)
AspNetCore.Views_SupplierRequest_Index.ExecuteAsync() in Index.cshtml
+
@(Html.Recaptcha(recaptchaSettings.Value))

appSettings.config:

"RecaptchaSettings": {
"SecretKey": "some_key",
"SiteKey": "some_key",
"Version": "v3" // tried to remove this line but exception is the same
},

Form won't submit if Captcha is above submit button

I have a dead simple contact form on an Asp.Net Core 2.2 brand new template.

<div class="row">
    <div class="col-lg-3"></div>
    <div class="col-lg-6">
        <h1>@ViewData["Title"]</h1>
        <form asp-route="Contact">
            <div class="form-group">
                <label for="email">Email</label>
                <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Email">
            </div>
            <div class="form-group">
                <label for="message">Message</label>
                <textarea name="message" class="form-control" id="message" rows="3"></textarea>
            </div>
            <div class="form-group">
                @using (Html.BeginForm("Contact", "Home"))
                {
                    @Html.Recaptcha(RecaptchaSettings.Value)
                }
              </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
</form></div></div>

The submit doesn't work. But if I change the order, it suddenly it works.

            <div class="form-group">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
            <div class="form-group">
                @using (Html.BeginForm("Contact", "Home"))
                {
                    @Html.Recaptcha(RecaptchaSettings.Value)
                }
              </div>

ReCAPTCHA settings null after using AddRecaptcha options

Hi..

Your fix for #60 has worked so far as it stops the application from crashing on runtime, however it seems the settings set using the options method do not persist when they are injected into a controller...

Read me example being used:

// Or configure recaptcha via options
services.AddRecaptcha(options =>
{
    options.SecretKey = "Your secret key";
    options.SiteKey = "Your site key";
});

image

I noticed this issue when trying to validate responses. The Validate(code) method was returning a new response object with all fields set to the default value. It may be worth throwing some sort of exception if a validation is attempted without a secret key..

image

Recaptcha host and request host do not match. Forgery attempt? v2-invis or v3

Hi,

I'm using v2.1.1 due to my ASP.Net Core is version 2.1, giving me troubles with upper versions. I need to use invisible captcha v2-invisible or V3, I tried to follow documentation, follow is Startup:

var recaptcha = Configuration.GetSection("RecaptchaSettings");
            if (!recaptcha.Exists())
                throw new ArgumentException("Missing RecaptchaSettings in configuration.");

services.Configure<RecaptchaSettings>(Configuration.GetSection("RecaptchaSettings"));
services.AddTransient<IRecaptchaService, RecaptchaService>();

Following is login view:

<form asp-area="Identity" asp-controller="Account" asp-action="Login" method="post" class="ffl-form" id="loginForm"> <h3>@Localizer["Ingrese al portal de SicotX"]</h3> <h6>@Localizer["con sus Credenciales"]</h6> <hr /> <div class="form-group"> <div class="ffl-wrapper"> <label asp-for="Usuario" class="ffl-label">@Localizer["Usuario"]</label> <input asp-for="Usuario" class="form-control" autocomplete="off" /> <span asp-validation-for="Usuario" class="text-danger"></span> </div> </div> <div class="form-group"> <div class="ffl-wrapper"> <label asp-for="Contraseña" class="ffl-label">@Localizer["Contraseña"]</label> <input asp-for="Contraseña" class="form-control" /> <span asp-validation-for="Contraseña" class="text-danger"></span> </div> </div> <div class="form-group"> @Html.Recaptcha(RecaptchaSettings?.Value) </div> <div class="form-group text-center"> <button id="recaptcha" type="submit" class="btn btn-primary">@Localizer["Ingresar"] <i class="fa fa-user"></i></button> </div> </form>

Following is Account controller for Login action:

public async Task<IActionResult> Login(LoginViewModel model) { var recaptcha = await _recaptcha.Validate(Request); if (!recaptcha.success) { ModelState.AddModelError("Error", _localizer["Hubo un error de validación del Captcha. Por favor intente nuevamente!"].Value); _logger.LogInformation($"Hubo un error de validación del Captcha."); }
I configured appSettings (I created 2 sites for v2 invisible and v3) with the correct sitekey and secretkey and version: v2-invis and throws the exception, as follows:

ValidationException: Recaptcha host, and request host do not match. Forgery attempt?
reCAPTCHA.AspNetCore.RecaptchaService.Validate(HttpRequest request, bool antiForgery) in RecaptchaService.cs
SicotX.Areas.Identity.Controllers.AccountController.Login(LoginViewModel model) in AccountController.cs
+
var recaptcha = await _recaptcha.Validate(Request);
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
SicotX.Startup+<>c+<b__6_1>d.MoveNext() in Startup.cs
+
await next();
SicotX.Startup+<>c+<b__6_0>d.MoveNext() in Startup.cs
+
await next();
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

I changed to correct sitekey and secretkey and v3 but for some reason my submit button dissapeared, no way to click on Login button, and javascript error is thrown:

Uncaught Error: reCAPTCHA placeholder element must be an element or id
at Object.Fd [as render] (www.gstatic.com/recaptcha/api2/v1554100419869/recaptcha__es_419.js:526)
at _eebca1b4_7f0d_4e74_b2e9_d5fba0580a53 (Login:268)
at $p (www.gstatic.com/recaptcha/api2/v1554100419869/recaptcha__es_419.js:516)
at iG (www.gstatic.com/recaptcha/api2/v1554100419869/recaptcha__es_419.js:517)
at www.gstatic.com/recaptcha/api2/v1554100419869/recaptcha__es_419.js:530
at www.gstatic.com/recaptcha/api2/v1554100419869/recaptcha__es_419.js:549

I don't know if I'm following nuget package documentation it not works. What am I doing wrong?

I would prefer to use V3, but not succeded. Thanks for any help!

Provide Html helper for non-form inclusion of recaptcha on pages

I'd like to include the recaptcha v3 on all my pages using my shared header, as recommended by Google.

I tried doing this with javascript but it's difficult to conditionally load the captcha when it hasn't been already included by the current Html helper.

What I'd recommend is having two helpers, one for loading all the scripts and another specifically for adding the recaptcha to a form. So, the form helper would use the existing scripts.

reCaptcha v3 token expires - no mechanism in place to prevent the issue

Hi,
I'm running into issues where the reCaptcha token expires.

After investigating I found that this project
the current implementation of this project is a bit problematic because it calls grecaptcha.execute on page load instead of on form submit. In real world scenarios we can expect the user to keep old tab around for prolonged period of time to use later and we can't expect the user to quickly fill all and every forms. This makes it extremely likely for the token to expire (it expires after 2 minutes) before the user submit the form.

Unfortunately this project doesn't let us define expiration callback (v3) to refresh the token nor does it let us call grecaptcha.execute on form submit. There's just no mechanism in place to prevent the problem.

See #30 as adding both expired and loaded callback support for v3 and releasing a new nugget version would fix those critical issues.

Need model validator before template binding

Need a way to validate models passed as T to see if they are missing certain values that can be defaulted. This should make it easy to supply partially constructed models such as only supplying Action in V3 and letting the validator / binder handle the defaults for the rest.

NetStandard

Hi,

Thank you for your awesome work.
I have a dotnet core projet with Target Full Framework 4.7.2.
Is it possible have an updated version of this package for .NET Standard Projects?
The Current version is not working with v3, because of the response is undefined, I saw is corrected, but not in .NET Standard version, (The latest available version in nuget.org is 2.1.1)

Thnak you again.

Using Webproxy

Hey,
i've got an error while valdiation process, cause webserver using a webproxy. How to configure proxy for valdiation process?
Best regards.
David

ContentSecurityPolicy options

Thanks for the great library.

Would you consider some support for handling ContentScurityPolicies as part of the library?

When I am integrating this, I need to adjust our CSP headers and add a few google sites (see https://developers.google.com/recaptcha/docs/faq#im-using-content-security-policy-csp-on-my-website.-how-can-i-configure-it-to-work-with-recaptcha). Would it be possible to allow for optionally setting the nonces to support both for the scripts loaded from google but also for the inline script (which seem to require the unsafe-line value to be added to the script-src)?

How do we change the action value.

Hi
How to change the Action attribute from 'homepage'.?

if (typeof grecaptcha !== 'undefined') {
	grecaptcha.ready(function () {
		grecaptcha.execute('fbfbfbfbfbfbfbfbfbfbfbfbfbfbfbfbf', { 'action': 'homepage' }).then(function (token) {
			document.getElementById('g-recaptcha-response').value = token;
		});
	});
}

How can I change recaptcha language?

In google recaptcha, there's hl attribute which shows language.

<script src="https://www.google.com/recaptcha/api.js?explicit&hl=nl"></script>

How can I use this feature?

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.