Google reCAPTCHA using HttpClient in ASP.NET
Introduction
reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart. With the new API, a significant number of your valid human users will pass the reCAPTCHA challenge without having to solve a CAPTCHA.
Building The Code
Before you start, visit this link https://www.google.com/recaptcha/intro/index.html and click on the Get reCAPTCHA button and follow the steps.
Let's Get started
Step 1: Create a class or a method in your controller and add the code below.
public async Task<string> GetRecaptcha(){var response = HttpContext.Current.Request["g-recaptcha-response"];const string secretKey = "your secret key";var apiConsumer = new ApiConsumer();const string url = "https://www.google.com/recaptcha/";apiConsumer.BaseUri = new Uri(url);apiConsumer.ContentType = ApiConsumer.ApplicationJson;apiConsumer.ResourcePath = string.Format("api/siteverify?secret={0}&response={1}", secretKey, response);var resp = await apiConsumer.GetAsync();if (resp.IsSuccessStatusCode){var result = await resp.Content.ReadAsStringAsync();return result;}return null;}
Step 2: You can now call this in your MVC controller method:
Note: I used the Netonsoft JObject to parse the server response.var recaptcha = await _utils.GetGoogleRecaptcha();var obj = JObject.Parse(recaptcha);var status = (bool)obj.SelectToken("success");if (status){//goto dashboard}//recaptcha failed
Refer to this url for the Apiconsumer class implementation http://techcerberus.blogspot.com.ng/2017/03/jwt-in-aspnet-web-api-and-mvc.html
Step 3: Adding the View
<script src='https://www.google.com/recaptcha/api.js' type="text/javascript"></script>
<div class="g-recaptcha" data-sitekey="sike key">
</div>The Result:
Comments
Post a Comment