Base solution for your next web application
Open Closed

Integrating reCaptch into new public site #12535


User avatar
0
4Matrix created

We are using v14.3 (ASP.Net Core + Angular) but want to put a reCaptcha on a custom Contact Us page in the Public site project. I can do this from scratch but I dont want to do this if it already has support built in and I am missing something?

Markdown is supported
Copy & paste or drag & drop images (max 30 MB per image)

3 Answer(s)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @4Matrix

    In Angular, the ReCaptchaV3WrapperService class is available for the reCAPTCHA feature. You can use this service to add reCAPTCHA to any page, and for validation operations, you can follow the logic of the sample login code below.

    Exampla Login ReCaptcha Flow

    login(): void {
        let recaptchaCallback = (token: string) => {
            this.showMainSpinner();
    
            this.submitting = true;
            this.loginService.authenticate(
                () => {
                    this.submitting = false;
                    this.hideMainSpinner();
                },
                null,
                token
            );
        };
    
        if (this._recaptchaWrapperService.useCaptchaOnLogin()) {
            this._recaptchaWrapperService
                .getService()
                .execute('login')
                .subscribe((token) => recaptchaCallback(token));
        } else {
            recaptchaCallback(null);
        }
    }
    
    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    4Matrix created

    Sorry, I know we can use it in the Angular site, I want to use it in the Public Site, e.g. <ProjectName>.Web.Public, which is an Asp.net Core MVC site I believe?

    We have the angular application on app.mywebsite.com and the Public application on www.mywebsite.com and we have a contact us page there we want to protext

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @4Matrix

    Thank you for the correction. To enable ReCaptcha on a Contact page or other page on a public website, you can add the following sample code to your form structure. To use it on a public website, you need to validate using the RecaptchaValidator under Web.Core. You can do this by setting an endpoint in the controller or using jQuery, then performing the validation.

    @section Scripts
    {
         @if (ViewBag.UseCaptcha)
        {
            <recaptcha-script-v3/>
            <recaptcha-script-v3-js action="YourPageAction" execute="false" />
        }
    }
    
    <form class="form public-contact-form" asp-action="SendContact" method="post">
         @if (ViewBag.UseCaptcha)
        {
            <input type="hidden" name="@RecaptchaValidator.RecaptchaResponseKey" id="recaptchaResponse"/>
        }
    
    </form>
    

    Example YourPage JavaScript File

    var CurrentPage = (function () {
      var handleContact = function () {
        var $form = $('.public-contact-form');
    
        $form.validate();
    
        $form.find('input').keypress(function (e) {
          if (e.which === 13) {
            if ($('.forget-form').valid()) {
              $('.forget-form').submit();
            }
            return false;
          }
        });
    
        $form.submit(function (e) {
          e.preventDefault();
    
          if (!$form.valid()) {
            return;
          }
    
          function setCaptchaToken(callback) {
            callback = callback || function () {};
            if (!abp.setting.getBoolean('App.UserManagement.UseCaptchaOnContactForm')) { //(Optional)
              callback();
            } else {
              grecaptcha.reExecute(function (token) {
                $('#recaptchaResponse').val(token);
                callback();
              });
            }
          }
    
          setCaptchaToken(function () {
            abp.ui.setBusy(
              null,
              abp
                .ajax({
                  contentType: app.consts.contentTypes.formUrlencoded,
                  url: $form.attr('action'),
                  data: $form.serialize(),
                })
                .done(function () {
                  abp.message
                    .success(app.localize('ContactSentErrorMessage'), app.localize('MailSent'))
                    .done(function () {
                      location.href = abp.appPath + '/Contact';  //Replace with your Host URL
                    });
                }),
            );
          });
        });
      };
    
      return {
        init: function () {
          handleContact();
        },
      };
    })();
    

    Example Your App Service

     public async Task SendContact(SendContactInput input)
     {
         if (UseCaptchaOnContactForm())
         {
             await RecaptchaValidator.ValidateAsync(input.CaptchaResponse);
         }
        //...
    }
    

    If you apply the example configuration provided here to your own scenario, you will integrate ReCaptcha into the form on your Public website. One point to note is that you need to send requests to the Host endpoint to access the AppService. In your JavaScript file, you can use Ajax to send requests to your AppService; you can handle it the same way you use the form in your own scenario.

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)