Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use google recaptcha with Angular and WebAPI

I'm using Angular js front end application and web API backend. I want to use google recaptcha in the front end application. I can get widget displayed by referring following URL. https://developers.google.com/recaptcha/docs/display. This document doesn't talk about server-side validation with the secret key. But I have noticed some asp.net developers use server side implementation to validate google recaptcha response with the secret key. Do I need to do server-side validation with the secret key and what is the best way to do that in relating to angular and web API?

like image 341
Yasith Avatar asked Feb 23 '17 22:02

Yasith


People also ask

How do I embed a Google reCAPTCHA?

Add Google reCAPTCHA to a formClick the pencil icon or Edit on the form or newsletter block. In the Storage tab, click Google reCAPTCHA. Switch the Use Google reCAPTCHA toggle on. Repeat these steps for all form blocks on your site where you want to add a reCAPTCHA.

Is Google reCAPTCHA an API?

reCAPTCHA Enterprise provides a frictionless user experience where fraud protection is easily extended across websites rather than being limited to select pages. It can be integrated into your mobile application using an API-based service.


1 Answers

Yes, you need to do server side validation otherwise your unauthenticated API endpoints aren't protected by direct calls that don't go through your website.

The solution is pretty straight-foward and is detailed here: https://developers.google.com/recaptcha/docs/verify

But a very simple example of a method that would validated the g-recaptcha-response given by the website would look like this:

    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(
            $"https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={encodedResponse}");

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

RecaptchaResponse is a simple class we have that looks like this:

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; }
}
like image 65
Mashton Avatar answered Oct 01 '22 05:10

Mashton