使用ASP.NET验证Localhost上的ReCaptcha(Javascript API)用户答案

时间:2012-11-20 06:13:06

标签: javascript asp.net localhost recaptcha

我在本地主机上的aspx页面上使用ReCaptcha和javascript API。我在某处读到只要我在localhost上使用它就不需要密钥。所以,我使用了一些我在某处找到的随机密钥。我可以成功地渲染recaptcha挑战。以下是我的javascript代码。

Recaptcha.create("6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf", 'captchadiv',
{
    tabindex: 1,
    theme: "clean",
    callback: Recaptcha.focus_response_field
});


//To Validate user response
function Recaptcha_IsCorrect()
{
    var xmlHttpRequest;
    var PageURL = document.URL;
    var xmlDoc;

    if (window.XMLHttpRequest)
    {
        xmlHttpRequest = new XMLHttpRequest();
    }
    else
    {
        xmlHttpRequest = new ActiveXObject("Microsoft.xmlHttpRequest");
    }

    var challenge = Recaptcha.get_challenge();
    var userResponse = Recaptcha.get_response();

    var url = "../Ajax/PIAsyncAjax.asmx/ValidateReCaptcha?clientIP=127.0.0.1&privateKey=6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf&challenge=" + challenge + "&response=" + userResponse;

    xmlHttpRequest.open("GET", url);
    xmlHttpRequest.onreadystatechange = function ()
    {
        if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
        {
            alert(xmlHttpRequest.responseText);
        }
    };

    xmlHttpRequest.send();
}    

以下是我的webservice代码,它暴露了webmethod以验证ReCaptcha用户输入。我收到错误“invalid-site-private-key”。

namespace YADA.YADAYADA{

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]   
public class PIAsyncAjax : System.Web.Services.WebService
{       
    [WebMethod]
    public string ValidateReCaptcha(string clientIP, string privateKey, string challenge, string response)
    {

        bool isValid = false;
        string validationResponse = "";

        reCaptchaValidation validator =
            new reCaptchaValidation(null,       
                                    clientIP,
                                    privateKey,
                                    challenge,
                                    response);

        isValid = validator.Validate();

        if (isValid)
        {
            validationResponse = "true";
        }
        else
        {
            if (!validator.IsErrored)
            {
                validationResponse = "false";
            }
            else
            {
                // oh dear, something not right

                if (validator.Exception != null)        // an exception occurred while 
                    // trying to validate
                    validationResponse = validator.Exception.ToString();
                else if (validator.ValidationResult != null)  // the validation web service 
                    // returned an error code 
                    // (other than an invalid captcha solution)
                    validationResponse = "web service error: " + validator.ValidationResult;
            }
        }

        return validationResponse;
    }
}


public class reCaptchaValidation
{
    private string challenge, response, privateKey, ip;
    private IWebProxy proxy;

    public reCaptchaValidation(string clientIP, string privateKey, 
    string challenge, string response) : this(null, clientIP, privateKey, 
    challenge, response) { }

    public reCaptchaValidation(IWebProxy proxy, string clientIP, 
        string privateKey, string challenge, string response)
    {
        this.proxy = proxy;
        this.ip = clientIP;
        this.privateKey = privateKey;
        this.challenge = challenge;
        this.response = response;
    }

    private bool _errored;
    public bool IsErrored
    {
        get
        {
            return _errored;
        }
    }

    private Exception _ex;
    public Exception Exception
    {
        get
        {
            return _ex;
        }
    }

    private string _vr;
    public string ValidationResult
    {
        get
        {
            return _vr;
        }
    }

    public bool Validate()
    {
        try
        {
            string post = "privatekey=" + HttpUtility.UrlEncode(privateKey) + 
        "&remoteip=" + HttpUtility.UrlEncode(ip) + "&challenge=" + 
        HttpUtility.UrlEncode(challenge) + "&response=" + 
        HttpUtility.UrlEncode(response);

            WebRequest wr = HttpWebRequest.Create
            ("http://www.google.com/recaptcha/api/verify");
            wr.Method = "POST";

            if (proxy != null)
                wr.Proxy = proxy;

            wr.ContentLength = post.Length;
            wr.ContentType = "application/x-www-form-urlencoded";
            using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
            {
                sw.Write(post);
                sw.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                string valid = sr.ReadLine();
                if (valid != null)
                {
                    if (valid.ToLower().Trim() == "false")
                    {
                        string errorcode = sr.ReadLine();

                        if (errorcode != null)
                        {
                            if (errorcode.ToLower().Trim() != "incorrect-captcha-sol")
                            {
                                _vr = errorcode;
                                _errored = true;
                                return false;
                            }
                        }
                    }

                    return (valid.ToLower().Trim() == "true");
                }
                else _vr = "empty web service response";

                sr.Close();
                return false;
            }
        }
        catch (Exception caught)
        {
            _errored = true;
            _ex = caught;
        }
        return false;
    }
}}

我做错了什么?我应该得到私钥吗?任何帮助都会很棒。

提前致谢, Venkat。

1 个答案:

答案 0 :(得分:0)

它适用于我刚刚创建的公钥和私钥。该死的,我只是假设,“localhost”在注册时不会被接受为合法的域名。