PaulMiami / reCAPTCHA

reCAPTCHA 2.0 for ASPNET Core
MIT License
134 stars 37 forks source link

Implementing reCAPTCHA using Razor Pages (.net core 2.0) #21

Closed Fleximex closed 7 years ago

Fleximex commented 7 years ago

I'm trying to use reCAPTCHA in my asp.net core 2.0 web application. With the the new Razor Pages MVVM you can move all logic to PageModel classes behind your cshtml page.

My problem is that when I post my form the ModelState is always valid. The captcha isn't included in the ModelState. My situation looks like this:

Register.cshtml @addTagHelper *, PaulMiami.AspNetCore.Mvc.Recaptcha on top of my page

``

` inside a form

`

<recaptcha-script validation-message-element-id="recaptchaErrorMessage" /> at the bottom of my page

(When I check the page source the script is generated)

jQuery in my layout page

Register.cshtml.cs

[BindProperty]
public RegisterViewModel Input { get; set; }

[ValidateRecaptcha]
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
    ReturnUrl = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = Input.Username, Email = Input.Email };
        var result = await _userManager.CreateAsync(user, Input.Password);
        if (result.Succeeded)
        {
            _logger.LogInformation("User created a new account with password.");

            await _signInManager.SignInAsync(user, isPersistent: false);
            return LocalRedirect(Url.GetLocalUrl(returnUrl));
        }
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
    }

    // If we got this far, something failed, redisplay form
    return Page();
}

In all the reCAPTCHA examples the ViewModel is given as an parameter in the IActionResult post method. I don't know how the [ValidateRecaptcha] annotation works but I suspect it injects the captcha result in the parameter and then when you call ModelState.IsValid it will also check the captcha.

I use a BindProperty however named input. Which I use for all the other inputs like this:

<label asp-for="Input.Username"></label>
<input asp-for="Input.Username" class="form-control" />
<span asp-validation-for="Input.Username" class="text-danger"></span>

Can someone tell me how to implement reCAPTCHA in this MVVM structure without using controllers.

Fleximex commented 7 years ago

I have now implemented Googles RECAPTCHA without this github project.

Instead of [ValidateRecaptcha] I have written the check myself.