Verify reCAPTCHA

In this post we are going to verify reCAPTCHA user value in server-side using ASP.Net Core API. Previously we enabled reCAPTCHA in client-side using Angular8. To overview that, follow the below link:

Clone the repository:

Using previous process, run the application. Let’s get start with modification of our existing code to submit HTTP Post request.

Form Submission:

Import:

import { HttpModule, Http, Request, RequestMethod, Response, RequestOptions, Headers } from '/http';
import { Observable} from 'rxjs';
import { map, catchError } from 'rxjs/operators';

Submit:

onSubmit()
{
    let _postUrl = 'http://localhost:50760/api/values/Validate';
    this.submitForm(this.reactiveForm.value, _postUrl)
        .subscribe(response => {  
            this.res = response;
            if(this.res.resdata.success)
            {
                this.resmessage = 'Verified Successfully!'
                this.reset();
            }
            else
            {
                this.resmessage = 'Verification Error!'
            }
        }, error => {
            console.log(error);
        });
}

//HTTP-POST Request
submitForm(model: any, postUrl: string): Observable {
    return this._http.post(postUrl, model)
        .pipe(map(res => res.json()))
        .pipe(catchError(this.handleError));
}

Verify:

// POST: api/Values/Validate
[HttpPost("[action]")]
public object Validate([FromBody]object data)
{
    object result = null; object resdata = null; string recaptchaReactive = string.Empty;
    //string siteKey = "6Lc8E8MUAAAAAJ6lY4GMJpJesd3_X-b23Xsapaxc";
    string secretKey = "6Lc8E8MUAAAAAKepybg5vyM5BJ6fuducTma2VDZK";

    try
    {
        reactiveForm _reactiveForm = JsonConvert.DeserializeObject(data.ToString());
        if (_reactiveForm != null)
        {
            recaptchaReactive = _reactiveForm.recaptchaReactive;
            var objClient = new HttpClient();
            //var client = new System.Net.WebClient();
            var googleReply = objClient.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, recaptchaReactive));
            var captchaResponse = JsonConvert.DeserializeObject(googleReply);
            resdata = captchaResponse;
        }
    }
    catch (Exception) { }
    return result = new
    {
        resdata
    };
}

Finally:

Hope this post is going to help, Thanks. Download/clone full source code from

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply