Skip to content

Instantly share code, notes, and snippets.

@johnboker
Last active April 4, 2016 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnboker/8eae9146cf1404a4b2fa77a53e21a046 to your computer and use it in GitHub Desktop.
Save johnboker/8eae9146cf1404a4b2fa77a53e21a046 to your computer and use it in GitHub Desktop.
Verify ReCaptcha responses server-side.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
namespace Antiyes
{
public class ReCaptcha
{
public static async System.Threading.Tasks.Task<SiteVerifyResponse> VerifyUserResponse(string secret, string response,
string remoteip = null, bool throwOnError = false, string verifyUrl = "https://www.google.com/recaptcha/api/siteverify")
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string> { { "secret", secret }, { "response", response } };
if (remoteip != null)
{
values.Add("remoteip", remoteip);
}
var postData = new FormUrlEncodedContent(values);
var postResponse = await client.PostAsync(verifyUrl, postData);
var responseString = await postResponse.Content.ReadAsStringAsync();
var verifyResponse = JsonConvert.DeserializeObject<SiteVerifyResponse>(responseString);
if (throwOnError)
{
if (verifyResponse.Errors != null && verifyResponse.Errors.Length > 0)
{
var errors = string.Join(", ", verifyResponse.Errors.Select(a => ErrorCodes[a]));
throw new ReCaptchaVerifyException(errors);
}
}
return verifyResponse;
}
}
public static Dictionary<string, string> ErrorCodes => new Dictionary<string, string> {
{ "missing-input-secret","The secret parameter is missing."},
{ "invalid-input-secret","The secret parameter is invalid or malformed."},
{ "missing-input-response","The response parameter is missing."},
{ "invalid-input-response", "The response parameter is invalid or malformed."}
};
public class ReCaptchaVerifyException : Exception
{
public ReCaptchaVerifyException() { }
public ReCaptchaVerifyException(string message) : base(message) { }
public ReCaptchaVerifyException(string message, Exception inner) : base(message, inner) { }
}
public class SiteVerifyResponse
{
[JsonProperty(PropertyName = "success")]
public bool Success { get; set; }
[JsonProperty(PropertyName = "challenge_ts")]
public DateTime ChallengeTimestamp { get; set; }
[JsonProperty(PropertyName = "hostname")]
public string Hostname { get; set; }
[JsonProperty(PropertyName = "error-codes")]
public string[] Errors { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment