Integrating google reCaptcha in Asp.Net MVC and AngularJS

How to integrate Google's reCaptcha & Asp.Net MVC implementation with angular directive to display google reCaptcha widget in a webpage with a simple steps

 

Posted: May 15, 2019. | By: mustafa

This tutorial will show you how to integrate Google's reCaptcha in your AngularJs projects.
We are going to add AngularJS and a view in Asp.Net MVC which will include the reCaptcha widget. The user will have to solve the captcha to be able to submit the form. Solving the captcha will give us the "g-captcha-response" which we will verify at the back-end.

For client-side implementation we are going to use angular-recaptcha library. I have made this angular implementation for google reCaptcha in Asp.Net MVC, however you can find the original article here having made good explanation by Rahil Shaikh.

Steps to follow

  1. SignUp for google reCaptcha
  2. Set up AngularJs project
  3. Adding javacript library
  4. Adding angular API call using g-captcha-response
  5. How to verify user’s response from Google
  6. Asp.Net MVC implementation for reCaptcha

 

SignUp for google reCaptcha

SignUp here - https://www.google.com/recaptcha/

Register your website domain to get public site key and a secret key, this will be used to communicate from your server to Google, make sure you keep it a secret.


Refer - https://codeworld53.blogspot.com/2019/05/how-to-integrate-google-recaptcha-with.html


Start AngularJs project in Asp.Net MVC

Download the angular-recaptcha library and include the js file in your project. You can download it from here.

https://github.com/VividCortex/angular-recaptcha/blob/master/release/angular-recaptcha.min.js

Adding javacript library in a view

Add reference to angular-recaptcha library in our html.

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-recaptcha.min.js"></script>

 

Include reCaptcha library provided by Google into your project.

<script src="https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit" async defer></script>

Include the above line in your head tag. The onload callback is necessary to notify angular-recaptcha library that reCaptcha api is ready for usage.


Now we are going to inject the vcRecaptcha as dependency into our angular module.

var app1 = angular
.module('Test_ReCaptcha', ['vcRecaptcha', 'angucomplete-alt']);

The angular-recaptcha library provides us with the vcRecaptchaService that has a getResponse() method, which provides us with g-captcha-response string after the user has successfully solved the captcha.

Next add vcRecaptchaService as a function parameter to our controller.

Add app.js file in our Asp.Net MVC project, making $http post request to server with g-captcha-response.

(function (app1) {
 'use strict';

app1.controller('SignUp ', function (vcRecaptchaService, $scope, $http) {
 $scope.userName = "";
 $scope.userEmail = "";
 $scope.Password = "";


$scope.publicKey = "-------------site-key-----------";

$scope.SignUp = function(){
 
 /* vcRecaptchaService.getResponse() gives you the g-captcha-response */
 
 if(vcRecaptchaService.getResponse() === ""){ //if string is empty
 alert("Please resolve the captcha and submit!")
 }else {
 var post_data = { //prepare payload for request
 "Name": $scope.userName,
 "Email": $scope.userEmail,
 "Password": $scope.Password,
 "Re_CaptchaResponse":vcRecaptchaService.getResponse() //send g-captcah-response to our server
 }
 
 
 /* MAKE AJAX REQUEST to our server with g-captcha-string */
 $http.post('/Home/SignUp',post_data).success(function(response){
 if(response.error === 0){
 alert(response.message);
 }else{
 alert("User verification failed");
 }
 })
 .error(function(error){
 
 })
 }
 }

})
 
 })(app1);
 

Note - In the above code we have added public site key as a angular variable, which we are going to use to initialize while declaring reCaptcha widget into our html. Also just add vc-recaptcha as an angular directive attribute to our html tag.

<!--Recaptcha Widget--->
<div vc-recaptcha key="publicKey"></div>


How to verify user’s response from Google

At our server when we receive the "g-captcha-response" string from our contact method API, we are going to verify the user’s response string from the API provided by google.

Url - https://www.google.com/recaptcha/api/siteverify

 

This api takes three parameters for the POST request.

  • secret : "————YOUR SECRET KEY ———"
  • response: g-captcha-response string received from the front-end.
  • remoteip: "—-THE USERS IP ADDRESS———–"

Asp.Net MVC implementation for reCaptcha

[HttpPost]
 public ActionResult SignUp(LoginModel model)
 {
 RecaptchaResponse response = ValidateCaptcha(qouteModel.ReCaptchaResponse);
 //ValidateCaptcha(Request["g-recaptcha-response"]);
 
 if (response.Success == false) // getting response from google reCaptcha.
 { 
 return Json(new { error = 1, message = "Error From Google ReCaptcha : " + response.ErrorCodes.ElementAt(0).ToString() });
 } 
 
 // save in db
 Utility.SendMail(model.EmailSubject, messageBody, sendEmail);
 return Json(new { error = 0, message = "User SignUp made successfully." });
 
 }
 
 
 public RecaptchaResponse ValidateCaptcha(string encodedResponse)
 {
 if (string.IsNullOrEmpty(encodedResponse)) return new RecaptchaResponse { Success = false };

var secret = "-------------secret-key-----------";;
 if (string.IsNullOrEmpty(secret)) return new RecaptchaResponse { Success = false };

var client = new System.Net.WebClient();

var googleReply = client.DownloadString(
 string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse ));

return JsonConvert.DeserializeObject<RecaptchaResponse>(googleReply);
 }

Here RecaptchaResponse is a simple class we have in added Asp.Net MVC model. And LoginModel model class in cs.

public class RecaptchaResponse
{
 [JsonProperty("success")]
 public bool Success { get; set; }

[JsonProperty("error-codes")]
 public IEnumerable<string> ErrorCodes { get; set; }

[JsonProperty("challenge_ts")]
 public DateTime ChallengeTs { get; set; }

[JsonProperty("hostname")]
 public string Hostname { get; set; }
}

public class LoginModel
 {
 public string Name { get; set; }
 public string Email { get; set; }
 public string Password { get; set; }
 public string Re_CaptchaResponse { get; set; }
 }
 

related posts

Back to top