Linked: Google reCAPTCHA Validator: Iteration II
I have also created a simple Google Recaptcha Validation class to handle verification.
I used some code from CodingFusion's post Google New reCaptcha I am not a robot using asp .net, but I have altered it so that it fit my use case, and to make it extendable and reusable.
Can I clean it up further?
public class ReCaptchaValidator
{
private readonly string _ReCaptchaSecret;
private readonly string _ReCaptchaSiteKey;
public List<string> ErrorCodes { get; set; }
public ReCaptchaValidator(string reCaptchaSecret)
{
_ReCaptchaSecret = reCaptchaSecret;
this.ErrorCodes = new List<string>();
}
public ReCaptchaValidator(string reCaptchaSecret, string reCaptchaSiteKey)
{
_ReCaptchaSecret = reCaptchaSecret;
_ReCaptchaSiteKey = reCaptchaSiteKey;
this.ErrorCodes = new List<string>();
}
public bool ValidateCaptcha(HttpRequest request)
{
var sb = new StringBuilder();
sb.Append("https://www.google.com/recaptcha/api/siteverify?secret=");
sb.Append(_ReCaptchaSecret);
sb.Append("&response=");
sb.Append(request.Form["g-recaptcha-response"]);
//client ip address
sb.Append("&remoteip=");
sb.Append(GetUserIp(request));
//make the api call and determine validity
using (var client = new WebClient())
{
var uri = sb.ToString();
var json = client.DownloadString(uri);
var serializer = new DataContractJsonSerializer(typeof(RecaptchaApiResponse));
var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
var result = serializer.ReadObject(ms) as RecaptchaApiResponse;
if (result == null)
{
return false;
}
else if (result.ErrorCodes != null)
{
foreach(var code in result.ErrorCodes)
{
this.ErrorCodes.Add(code.ToString());
}
return false;
}
else if (!result.Success)
{
return false;
}
else //-- If successfully verified.
{
return true;
}
}
}
//--- To get user IP(Optional)
private string GetUserIp(HttpRequest request)
{
var visitorsIpAddr = string.Empty;
if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
visitorsIpAddr = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
else if (!string.IsNullOrEmpty(request.UserHostAddress))
{
visitorsIpAddr = request.UserHostAddress;
}
return visitorsIpAddr;
}
}
[DataContract]
public class RecaptchaApiResponse
{
[DataMember(Name = "success")]
public bool Success;
[DataMember(Name = "error-codes")]
public List<string> ErrorCodes;
}
DataContract
s for mine, that's a good write! \$\endgroup\$