Wednesday, May 15, 2019

How to integrate Google reCAPTCHA with Angular And Asp.Net MVC

Choosing the type of reCAPTCHA

There are four types of reCAPTCHA to choose from when creating a new site.


Selecting second method reCAPTCHA V2 -
The "I'm not a robot" Checkbox requires the user to click a checkbox for verifying that the user is not a robot. This will either pass the user immediately (with No CAPTCHA) or challenge them to validate whether or not they are human. This is simple way to integrate and requires two lines of html code.

How to generate secret key and site key

Sign up for a google reCAPTCHA and add your site domain 

Asp.Net Implementation for google reCaptcha

With asp.net we use server side implementation to validate for google recaptcha with the secret key. We  need to do server-side validation with the secret key.

For documentation about google reCAPTCHA visit url - https://developers.google.com/recaptcha/docs/verify.

Here is a simple Asp.net mvc method that helps to validate g-recaptcha-response which I have referred from stackoverflow questions.

public bool Validate(string encodedResponse)
    {
if (string.IsNullOrEmpty(encodedResponse)) return false; var secret = **your secret**;
if (string.IsNullOrEmpty(secret)) return 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(googleReply).Success; }
}

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


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

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

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

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

Each reCAPTCHA user response token is valid for two minutes, and can only be verified once to prevent replay attacks. If you need a new token, you can re-run the reCAPTCHA verification.

API Request
URL: https://www.google.com/recaptcha/api/siteverify

METHOD: POST

REQUEST PARAMETER:

secret Required. The shared key between your site and reCAPTCHA.
response Required. The user response token provided by the reCAPTCHA client-side integration on your site.
remoteip Optional. The user's IP address.

No comments:

Post a Comment

How to Unit Test in Asp.Net C#

Unit Testing in DotNet C# Testing Frameworks in DotNet XUint - Most Popular testing framework is xUnit, which is now part of the open source...