ReCaptcha

From Logic Wiki
Jump to: navigation, search

ReCaptchaCheck.cs

using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace VDSCore.Client.TheVDS.Shared
{
    public class ReCaptchaCheck
    {
 
 
        public static string Validate(string EncodedResponse, string PrivateKey)
        {
            var client = new System.Net.WebClient();

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

            var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ReCaptchaCheck>(GoogleReply);

            return captchaResponse.Success.ToLower();
        }

        [JsonProperty("success")]
        public string Success
        {
            get { return m_Success; }
            set { m_Success = value; }
        }

        private string m_Success;
        [JsonProperty("error-codes")]
        public List<string> ErrorCodes
        {
            get { return m_ErrorCodes; }
            set { m_ErrorCodes = value; }
        }


        private List<string> m_ErrorCodes;
    }
}

cshtml

<head>
  <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
        <div class="form-group col-sm-6">
            <div class="g-recaptcha" data-sitekey="6Lc37XcUAAAAACpU5FLp37ZOAsbLYRNtZl75Br89" data-callback="enableBtn"></div>
            <span class="field-validation-valid" data-valmsg-for="Captcha" data-valmsg-replace="true"></span>
        </div>
        <div class="form-group col-sm-6" style="text-align: right">
            <button type="submit" class="btn btn-primary" id="SendButton">Send Message<span></span></button>
        </div>

<script>
        document.getElementById("SendButton").disabled = true;
        function enableBtn(){
            document.getElementById("SendButton").disabled = false;
        }
    </script> 

Form Post

    string EncodedResponse = Request.Form["g-Recaptcha-Response"];
            string PrivateKey = _configuration.GetSection("AppSettings")["CaptchaSecret"];

            bool IsCaptchaValid = (ReCaptchaCheck.Validate(EncodedResponse, PrivateKey) == "true" ? true : false);
            if (!IsCaptchaValid)