Using ReCaptcha v3 in MVC Net Core 2 Applications
/Views/Shared/_reCaptcha.cshtml
@using Microsoft.Extensions.Configuration @inject IConfiguration _configuration <script src="https://www.google.com/recaptcha/api.js?render=@_configuration.GetSection('Recaptcha_v3')['SiteKey']"></script> grecaptcha.ready(function () { var $form = getForm(); if ($form.length == 0) { $(".grecaptcha-badge").hide(); } else { $form.on("submit", function(e){ e.preventDefault(); submitWithUserResponseToken($form); }); } }); function getForm() { return $("form").eq(0); } function submitWithUserResponseToken($form) { if ($form.length > 0) { grecaptcha.execute('@_configuration.GetSection("Recaptcha_v3")["SiteKey"]', { action: $form.attr('name') }).then
(function (userResponseToken) {
// v3: You have to manually append g-recaptcha-response to the posted form. // v2: g-recaptcha-response will be automatically added to the posted form. You can't manually add it. $form.append($('<input />').attr({ 'type': 'hidden', 'name': 'g-recaptcha-response', 'value': userResponseToken })); // Use the original submit() rather than jqeury's submit(),
// else the onsubmit event still will be fired by submit() (infinite loop). // https://github.com/google/recaptcha/issues/281 $form[0].submit(); }); } } <environment include="Development,Staging"> <div class="row"> <div class="col"> <input class="enabled float-left" onclick="viewReCaptchaAPIResponseToken()" type="button" value="Test reCaptcha" /> </div> </div> <script> function viewReCaptchaAPIResponseToken() { var $form = getForm(); $form.attr("action", "/Requests/ViewReCaptchaAPIResponseToken"); submitWithUserResponseToken($form); } </script> </environment>
Other files
Other files are the same as v2 Invisible. Please see https://spdaytoday.blogspot.com/2019/07/using-recaptcha-v2-insible-in-mvc-net.htmlThe reason we didn't choose ReCaptcha v3
- Unreliable: https://github.com/google/recaptcha/issues/248
- No fallback challenge available (In contrast, v2 will automatically challenge users with images or audio puzzles if v2 thought you were a bot)
- V3 is based on machine learning (e.g. the patterns most human users visit the site) and said suitable for high traffic sites, but this is not the case for our forms.
V2 Invisible might be the best bet till this writing. This v3 code worked but it might need some improvement as v3 was finally given up in my production apps. Instead, details have been taken into account in the v2 Invisible code.
Comments
Post a Comment