Google Invisible reCAPTCHA in ASP.NET MVC 5 Using Action Filters

Google's Invisible reCAPTCHA in ASP.NET MVC 5 Using Action Filters

In this post I will explains how to enable and customize the Invisible reCAPTCHA on your webpage and we can enable and customize the Invisible reCAPTCHA in to two ways.

Google's New Invisible reCAPTCHA in MVC Using Action Filters -

Step 1 - Go to URL https://www.google.com/recaptcha/admin and login with your credentials
Step 2 - Register the reCAPTCHA for your site with your site Label.

Select your Invisible reCAPTCHA radio button. After selecting Invisible reCAPTCHA, we will need to add your Domains mane where you want to add this Invisible reCAPTCHA and click on register with terms of services.

For example - My added domain is - localhost and site Label is - test. You can see the above steps for the same.


Step 3 - Client side integration -
 Add Script Bundle in the Bundle
  bundles.Add(new ScriptBundle("~/bundles/recaptcha", "//www.google.com/recaptcha/api.js").Include("~/Scripts/recaptcha-api.js"));

HTML page-
@model LoginViewModel
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "", role = "form", id = "LoginForm" }))
{
    <div class="form-group" id="loginSection">
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", placeholder = "Email", id = "txtEmail", autofocus = "autofocus" })
        @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
    </div>
    <div class="clr_10"></div>
    <button class="g-recaptcha btn btn-default"
            data-sitekey="@Model.RecaptchaPublicKey"
            data-callback="OnSubmit">
        Generate Pass Code
    </button>
}

And Load JavaScript API

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/recaptcha")
    <script>
                        function OnSubmit(token) {
                                    document.getElementById("LoginForm").submit();
                        }
    </script>
}

AND

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "Email")]
        [EmailAddress]
        public string Email { get; set; }

        //[Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }

        public string RecaptchaPublicKey { get; }

        public LoginViewModel() { }

        public LoginViewModel(string recaptchaPublicKey)
        {
            RecaptchaPublicKey = recaptchaPublicKey;
        }
    }

Step 4 - Install Autofac and Autofac.MVC5 using Nuget package manager in the portal app.
Step 5 - Create Invisible reCAPTCHA Validation Service

Interface -
public interface ICaptchaValidationService
    {
        bool Validate(string response);
    }

Interface implementation -
public class InvisibleRecaptchaValidationService : ICaptchaValidationService
    {
        private const string API_URL = "https://www.google.com/recaptcha/api/siteverify";
        private readonly string _secretKey;

        public InvisibleRecaptchaValidationService(string secretKey)
        {
            _secretKey = secretKey;
        }

        public bool Validate(string response)
        {
            if (!string.IsNullOrWhiteSpace(response))
            {
                using (var client = new WebClient())
                {
                    var result = client.DownloadString($"{API_URL}?secret={_secretKey}&response={response}");
                    return ParseValidationResult(result);
                }
            }

            return false;
        }

        private bool ParseValidationResult(string validationResult) => (bool)JObject.Parse(validationResult).SelectToken("success");
    }

Step 6 - Create Validate reCAPTCHA on the Server using this custom Attribute
    public class ValidateRecaptchaAttribute : ActionFilterAttribute
    {
        private const string RECAPTCHA_RESPONSE_KEY = "g-recaptcha-response";

        public ICaptchaValidationService CaptchaService { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var isValidate =   new InvisibleRecaptchaValidationService(ConfigurationManager.AppSettings["RecaptchaSecretKey"]).Validate(filterContext.HttpContext.Request[RECAPTCHA_RESPONSE_KEY]);
            if (!isValidate)
                filterContext.Controller.ViewData.ModelState.AddModelError("Recaptcha", "Captcha validation failed.");
        }
    }

Step 7 -
    //GET: /Account/Login
    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Index", "Home");
        }

        return View(new LoginViewModel(ConfigurationManager.AppSettings["RecaptchaPublicKey"]));
    }

Step 8 -
     //POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateRecaptcha]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {

        }

        return View("Login");
    }

Step 9 - Add the below code in the config file.
    <add key="RecaptchaSecretKey" value="6Lcf****AAAEJN**EPRU***" />
    <add key="RecaptchaPublicKey" value="****b27MgXmNmu2****OocE" />
     
AND

<dependentAssembly>
        <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.6.1.0" newVersion="4.6.1.0" />
      </dependentAssembly>
    </assemblyBinding>

Live Results –

References -

I hope you are enjoying with this post! Please share with you friends. Thank you so much!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^