Recaptcha Validate 的 JavaScript、JQuery 或 AJAX 版本

发布于 2024-11-09 01:40:52 字数 1552 浏览 0 评论 0原文

我尝试使用一些 js 代码验证 recaptcha,但收到一些权限错误“访问被拒绝” 是否可以使用 javascript 验证代码和 ajax 跨多个浏览器来实现验证。

<script type="text/javascript">


    $(document).ready(function() {

        Recaptcha.create("var_public_key", recaptchadiv, {
            theme: "clean",
            callback: Recaptcha.focus_response_field
        });
    });


function submitFormData() {

var urlString = "http://www.google.com/recaptcha/api/verify";
var params = encodeURI("remoteip=" + $("#userIp").val() +"&privatekey=" + var_private_key + "&challenge=" + Recaptcha.get_challenge() + "&response=" +
Recaptcha.get_response());
        params = encodeURI(params);
        var status = document.getElementById("status");
        status.className = "";
        status.innerHTML = "<b>Submitting your data. Please wait...</b>";
        var html = $.ajax({
            type: "POST",
            url: urlString + "?" + params,
            async: false
        }).responseText;

        alert("ResponseText: " + html + ", Recaptcha.responseText: " + Recaptcha.responseText);

        var result = html.split("\n")[0];

        if (result == "true") {
            status.innerHTML = " ";
            return true;
        }
        else {
            status.className = "GlobalErrorText";
            status.innerHTML = "Your captcha is incorrect. Please try again";
            Recaptcha.reload();
            return false;
        }
    }
</script>

am trying to validate the recaptcha using some js code but am getting some permission Errors "Access is Denied"
Is it possible to achieve the validation using the javascript validation code alongside ajax across multiple browsers.

<script type="text/javascript">


    $(document).ready(function() {

        Recaptcha.create("var_public_key", recaptchadiv, {
            theme: "clean",
            callback: Recaptcha.focus_response_field
        });
    });


function submitFormData() {

var urlString = "http://www.google.com/recaptcha/api/verify";
var params = encodeURI("remoteip=" + $("#userIp").val() +"&privatekey=" + var_private_key + "&challenge=" + Recaptcha.get_challenge() + "&response=" +
Recaptcha.get_response());
        params = encodeURI(params);
        var status = document.getElementById("status");
        status.className = "";
        status.innerHTML = "<b>Submitting your data. Please wait...</b>";
        var html = $.ajax({
            type: "POST",
            url: urlString + "?" + params,
            async: false
        }).responseText;

        alert("ResponseText: " + html + ", Recaptcha.responseText: " + Recaptcha.responseText);

        var result = html.split("\n")[0];

        if (result == "true") {
            status.innerHTML = " ";
            return true;
        }
        else {
            status.className = "GlobalErrorText";
            status.innerHTML = "Your captcha is incorrect. Please try again";
            Recaptcha.reload();
            return false;
        }
    }
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏花。依旧 2024-11-16 01:40:52

@Boug是对的,这称为跨站点ajax请求,您可以查看这个问题,看看是否可以找到解决方案跨站点 AJAX 请求 但是....

我认为将您的 recaptcha 私钥放在 javascript 中是一个漏洞,recaptcha 应该在服务器端代码上进行验证,这个问题包含有关如何实现 recaptcha 的有用链接在 Asp.Net MVC 如何为 ASP.NET MVC 实现 reCaptcha?< /a> 我使用了这种方法,效果非常好 http://www .dotnetcurry.com/ShowArticle.aspx?ID=611&AspxAutoDetectCookieSupport=1

@Boug is right, this is called cross site ajax request, you can see this question to see if you can a find a solution Cross-site AJAX requests but....

I think putting your private key for recaptcha in javascript is a vulnerability, recaptcha should be validated on Server Side code, this question contain useful links about how to implement recaptcha in Asp.Net MVC How to implement reCaptcha for ASP.NET MVC? I used this approach and it works perfectly http://www.dotnetcurry.com/ShowArticle.aspx?ID=611&AspxAutoDetectCookieSupport=1

极度宠爱 2024-11-16 01:40:52

您收到权限错误是因为您的ajax代码正在尝试访问与您的脚本不同的站点(google)上的脚本。据我所知,出于安全原因,我认为您不能进行跨站点 Ajax 调用

You are getting permission error because your ajax code is trying to access a script on a different site (google) as your script. From what I know, I dont think you can do cross site Ajax calls for security reasons

耳钉梦 2024-11-16 01:40:52

这个问题已经有了答案。但是,这里添加了一些可在 ASP.NET WebForms 中使用的代码,这些代码使您能够向带有 reCaptcha 控件的页面发出本地 AJAX 请求,然后执行服务器端验证码验证。该页面的 Web 方法将返回 true/false。

我从 mindfire 解决方案,但在Ajax成功回调中添加了JS函数的执行b/c Ajax正在进行异步回调。

Javascript:

<script type="text/javascript">
$(function(e) {
    $("#submit").click(function() { // my button is type=button, not type=submit
        // I'm using jQuery validation and want to make sure page is valid before making Ajax request
        if ( $("#aspnetForm").valid() ) {
            validateCaptcha();  // or validateCaptchaJson() if you want to use Json
        }   // end  If ($("#aspnetForm").valid())
    }); // end $("#submit").click()
}); // end $(function(e)


function validateCaptcha() {
    // Individual string variables storing captcha values
    var challengeField = $("input#recaptcha_challenge_field").val();
    var responseField = $("input#recaptcha_response_field").val();

    // Ajax post to page web method that will do server-side captcha validation
    $.ajax({
        type: "POST",
        url: "page.aspx/ValidateCaptcha",
        data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
        async: false
        success: function(msg) {
            if(msg.d) { // Either true or false, true indicates CAPTCHA is validated successfully.
                // this could hide your captcha widget
                $("#recaptcha_widget_div").html(" ");
                // execute some JS function upon successful captcha validation
                goodCaptcha();
            } else {
                // execute some JS function upon failed captcha validation (like throwing up a modal indicating failed attempt)
                badCaptcha();
                // don't forget to reload/reset the captcha to try again
                Recaptcha.reload();
            }
            return false;
        }
    });
}

function validateCaptchaJson() {
    // JavaScript object storing captcha values
    var captchaInfo = {
        challengeValue: Recaptcha.get_challenge(),
        responseValue: Recaptcha.get_response()
    };

    // Ajax post to page web method that will do server-side captcha validation
    $.ajax({
        type: "POST",
        url: "page.aspx/ValidateCaptcha",
        data: JSON.stringify(captchaInfo),  // requires ref to JSON (http://www.JSON.org/json2.js)
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if(msg.d) { // Either true or false, true indicates CAPTCHA is validated successfully.
                // this could hide your captcha widget
                $("#recaptcha_widget_div").html(" ");
                // execute some JS function upon successful captcha validation
                goodCaptcha();
            } else {
                // execute some JS function upon failed captcha validation (like throwing up a modal indicating failed attempt)
                badCaptcha();
                // don't forget to reload/reset the captcha to try again
                Recaptcha.reload();
            }
            return false;
        }
    });
}
</script>

页面的 Web 方法 (VB.NET):

<WebMethod()> _
Public Shared Function ValidateCaptcha(ByVal challengeValue As String, ByVal responseValue As String) As Boolean
    ' IDEA: Get Private key of the CAPTCHA from Web.config file.
    Dim captchaValidtor As New Recaptcha.RecaptchaValidator() With { _
     .PrivateKey = "your_private_key_goes_here", _
     .RemoteIP = HttpContext.Current.Request.UserHostAddress, _
     .Challenge = challengeValue, _
     .Response = responseValue _
    }

    ' Send data about captcha validation to reCAPTCHA site.
    Dim recaptchaResponse As Recaptcha.RecaptchaResponse = captchaValidtor.Validate()
    ' Get boolean value about Captcha success / failure.
    Return recaptchaResponse.IsValid
End Function

The question has already been answered. But, here's some added code that will work in ASP.NET WebForms, which enables you to make a local AJAX request to the page w/ the reCaptcha control, then do server-side captcha validation. The page's web method will return true/false.

I got this code from mindfire solutions, but added the execution of JS functions in the Ajax success callback b/c Ajax is making async callbacks.

Javascript:

<script type="text/javascript">
$(function(e) {
    $("#submit").click(function() { // my button is type=button, not type=submit
        // I'm using jQuery validation and want to make sure page is valid before making Ajax request
        if ( $("#aspnetForm").valid() ) {
            validateCaptcha();  // or validateCaptchaJson() if you want to use Json
        }   // end  If ($("#aspnetForm").valid())
    }); // end $("#submit").click()
}); // end $(function(e)


function validateCaptcha() {
    // Individual string variables storing captcha values
    var challengeField = $("input#recaptcha_challenge_field").val();
    var responseField = $("input#recaptcha_response_field").val();

    // Ajax post to page web method that will do server-side captcha validation
    $.ajax({
        type: "POST",
        url: "page.aspx/ValidateCaptcha",
        data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
        async: false
        success: function(msg) {
            if(msg.d) { // Either true or false, true indicates CAPTCHA is validated successfully.
                // this could hide your captcha widget
                $("#recaptcha_widget_div").html(" ");
                // execute some JS function upon successful captcha validation
                goodCaptcha();
            } else {
                // execute some JS function upon failed captcha validation (like throwing up a modal indicating failed attempt)
                badCaptcha();
                // don't forget to reload/reset the captcha to try again
                Recaptcha.reload();
            }
            return false;
        }
    });
}

function validateCaptchaJson() {
    // JavaScript object storing captcha values
    var captchaInfo = {
        challengeValue: Recaptcha.get_challenge(),
        responseValue: Recaptcha.get_response()
    };

    // Ajax post to page web method that will do server-side captcha validation
    $.ajax({
        type: "POST",
        url: "page.aspx/ValidateCaptcha",
        data: JSON.stringify(captchaInfo),  // requires ref to JSON (http://www.JSON.org/json2.js)
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            if(msg.d) { // Either true or false, true indicates CAPTCHA is validated successfully.
                // this could hide your captcha widget
                $("#recaptcha_widget_div").html(" ");
                // execute some JS function upon successful captcha validation
                goodCaptcha();
            } else {
                // execute some JS function upon failed captcha validation (like throwing up a modal indicating failed attempt)
                badCaptcha();
                // don't forget to reload/reset the captcha to try again
                Recaptcha.reload();
            }
            return false;
        }
    });
}
</script>

Page's Web Method (VB.NET):

<WebMethod()> _
Public Shared Function ValidateCaptcha(ByVal challengeValue As String, ByVal responseValue As String) As Boolean
    ' IDEA: Get Private key of the CAPTCHA from Web.config file.
    Dim captchaValidtor As New Recaptcha.RecaptchaValidator() With { _
     .PrivateKey = "your_private_key_goes_here", _
     .RemoteIP = HttpContext.Current.Request.UserHostAddress, _
     .Challenge = challengeValue, _
     .Response = responseValue _
    }

    ' Send data about captcha validation to reCAPTCHA site.
    Dim recaptchaResponse As Recaptcha.RecaptchaResponse = captchaValidtor.Validate()
    ' Get boolean value about Captcha success / failure.
    Return recaptchaResponse.IsValid
End Function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文