How to use Recaptcha V3 in MVC

If you don’t know what Google’s reCaptcha is, in summary, reCaptcha protects you from spam and other automated abuse.

To start using reCAPTCHA, you need to sign up with Google and register to obtain a pair of API keys for your site. The key pair consists of a site key and a secret key. The website key is used to call the reCAPTCHA service on your website or mobile application. The secret key authorizes communication between the application back-end and the reCAPTCHA server to verify the user’s response. The secret key must be kept secure for security purposes.

Now that we have obtained our keys, let’s start by implementing reCaptcha in a standard form. Once we have the form, we will modify it from there.

Create a Model

First, we will create a Model with the relevant fields for our form:

public class ContactUsViewModel{
public long Id { get; set; }
[Required]
public string Name { get; set; }
Required, EmailAddress]
public string Email { get; set; }
[DisplayName("Company (optional)")]
public string Company { get; set; }
[Phone, DisplayName("Phone (optional)")]
public string Phone { get; set; }
[DisplayName("Website (optional)")]
public string Website { get; set; }
[Required]
public string Description { get; set; }
}

Create a View

Then, we create our View:

@model ContactUsViewModel


@using (Html.BeginForm()){
<div>@Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name)</div>
<div>@Html.LabelFor(m => m.Email) @Html.TextBoxFor(m => m.Email)</div>
<div>@Html.LabelFor(m => m.Company) @Html.TextBoxFor(m => m.Company)</div>
<div>@Html.LabelFor(m => m.Phone) @Html.TextBoxFor(m => m.Phone)</div>
<div>@Html.LabelFor(m => m.Website) @Html.TextBoxFor(m => m.Website)</div>
<div>@Html.LabelFor(m => m.Description) @Html.TextAreaFor(m => m.Description</div>

    <input type=”submit” value=”send it our way” />

}

And finally the Controller

public class ContactController : Controller{
   public ViewResult Index()
   {
      return View();
   }
   [HttpPost]
   public ViewResult Index(ContactViewModel model)
   {
      if (ModelState.IsValid){
         //do your processing here
         return View("Thanks");
      }
      return View();
   }
}

Now we have all the code needed to process a form, we have to add reCAPTCHA to our form. The change in our View is very easy:

@model ContactUsViewModel

@using (Html.BeginForm()){
<div>@Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name)</div>
<div>@Html.LabelFor(m => m.Email) @Html.TextBoxFor(m => m.Email)</div>
<div>@Html.LabelFor(m => m.Company) @Html.TextBoxFor(m => m.Company)</div>
<div>@Html.LabelFor(m => m.Phone) @Html.TextBoxFor(m => m.Phone)</div>
<div>@Html.LabelFor(m => m.Website) @Html.TextBoxFor(m => m.Website)</div>
<div>@Html.LabelFor(m => m.Description) @Html.TextAreaFor(m => m.Description</div>

@Html.HiddenFor(m => m.GoogleCaptchaToken)

<input type=”submit” value=”send it our way” />
}

<script>
grecaptcha.ready(function () {
grecaptcha.execute('_reCaptchaSiteKey"]', { action: 'contact-us' }).then(function (token) {
$("#GoogleCaptchaToken").val(token);
});
});
</script>

It is also necessary to change the Model to add the Captcha Token:

public class ContactUsViewModel{
public long Id { get; set; }
[Required]
public string Name { get; set; }
Required, EmailAddress]
public string Email { get; set; }
[DisplayName("Company (optional)")]
public string Company { get; set; }
[Phone, DisplayName("Phone (optional)")]
public string Phone { get; set; }
[DisplayName("Website (optional)")]
public string Website { get; set; }
[Required]
public string Description { get; set; }
public string GoogleCaptchaToken { get; set; }
}

Now it is necessary to validate the Token on the server side:

public class ContactController : Controller{

   public ViewResult Index()
{
return View();
}
[HttpPost]
public ViewResult Index(ContactViewModel model)
{
if (ModelState.IsValid && !IsCapthaValid(model.GoogleCaptchaToken)){
//do your processing here
return View("Thanks");
}
return View();
}
private bool IsCapthaValid(string response)
{
bool isValid = false;
try
{
string secretKey = "reCaptchaSecretKey";
var client = new WebClient();
var result = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
var obj = JObject.Parse(result);

var success = (bool)obj.SelectToken(“success”);
var score = (float)obj.SelectToken(“score”);
if (success && score >= 0.5)
{
isValid = true;
}
}
catch
{
return false;
}
return isValid;
}
}

Ready to enhance your MVC experience?

Contact us for:

  • Intranet and Portals: Personalized solutions just for you.
  • Application Development: Intuitive, scalable, and secure solutions.
  • Consultancy Services: Expert advisory solutions.
  • Outsourcing: Maximize productivity.
  • Support and Maintenance: Keep your applications running seamlessly.
 

If you are interested in learning more about us and how we can help you, contact us

You can also check out our blog for more articles and insights on  Microsoft 365 technologies.