【问题标题】:Rendering reCaptcha V2.0 widget within Marionette Itemview在 Marionette Itemview 中渲染 reCaptcha V2.0 小部件
【发布时间】:2018-04-04 20:04:42
【问题描述】:

这将是我提出问题并提出解决方案的帖子 由于遇到了几次麻烦并环顾四周,我决定将我的最终解决方案发布给其他人以从中获利。

问题: 如何渲染 google 的 reCaptcha v2.0 小部件并在带有 java 后端的 Marionettejs 应用程序中对其进行验证。

【问题讨论】:

    标签: javascript java recaptcha marionette captcha


    【解决方案1】:

    在通用步骤并按照谷歌指南呈现重新验证码之后,我的验证码仍然没有呈现,所以我的解决方案来了:

    渲染验证码和包含脚本都是在 itemview 的 onRender 函数中完成的:

        'text!login/templates/form.html',
        'app'
    ], function (app, Marionette, Backbone, _, $, Handlebars, FormTemplate) {
     return Marionette.ItemView.extend({
    
        template: Handlebars.compile(FormTemplate),
    
        ui: {
            form: '
        },
    
        events: {
            'submit @ui.form': 'onSubmit'
        },
    
        onRender: function() {
          this.loadCaptcha();
        },
    
        loadCaptcha: function() {
            var self = this;
            var getRecaptchaResponse = function(response) {
                self.captchaResponse = response;
            };
    
            window.renderCaptcha = function () {
                self.captchaWidgetId = grecaptcha.render('yourCaptchaDiv', {
                    sitekey: 'YourSiteKey',
                    callback: getRecaptchaResponse
                });
            };
    
            $.getScript('https://www.google.com/recaptcha/api.js?onload=renderCaptcha&render=explicit', function() {});
        },
    ...
    }
    

    我尝试了其他加载脚本的方法,但出现了一些错误,例如脚本在 div 之前加载,或者浏览器说 de Dom 已完全加载,但 onRender 在之后调用

    我必须为要加载的验证码小部件包含一个 div,这是在 form.html

    <div id="reCaptcha" class="btn"></div>
    

    这将呈现您的小部件,现在您需要验证它已被填充并且它是谷歌的有效用户响应,为此我使用相同的模块并使用下一个功能:

    onSubmit: function (e) {
    //only act if the captcha has been filled - This could be easily erased from a browser, but a back end verification takes place too
                if (grecaptcha.getResponse() !== "") {
                    e.preventDefault();
                    var _view = this;
                    this.blockForm();
                    $.ajax({
                        url: 'yourLoginService',
                        type: 'POST',
                        data: {
                            userLogin: this.ui.user.val(),
                            userPassword: this.ui.password.val(),
                            //get the captcha response
                            captchaResponse: grecaptcha.getResponse()
                        }
    
                    }).done(function (data) {
                        app.router.navigate('', {trigger: true});
                        _view.destroy();
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                      // your fail handling
                    });
                }
            },
    

    接下来是使用 google 提供的密钥验证您的验证码服务器端的时候了(注意这是一个 Java6 应用程序,因此异常处理很麻烦):

    //some other imports ignored
    import org.apache.commons.io.IOUtils;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    class Captcha {
    
        private static final String CAPTCHA_SECRET_KEY = "YourSecretKey";
        private static final Logger LOGGER = Logger.getLogger(Captcha.class);
    
        static boolean isCaptchaValid(String response) {
            try {
                String url = "https://www.google.com/recaptcha/api/siteverify?"
                        + "secret=" + CAPTCHA_SECRET_KEY
                        + "&response=" + response;
    
                InputStream res = new URL(url).openStream();
                JSONObject json = new JSONObject(getJsonResponse(res));
                res.close();    
                return json.getBoolean("success");
            } catch (JSONException e) {
                LOGGER.error("Can not parse captcha response Json: " + e);
                return false;
            } catch (MalformedURLException e) {
                LOGGER.error("Malformed URL: " + e);
                return false;
            } catch (IOException e) {
                LOGGER.error("Error reading response from captcha verification response: " + e);
                return false;
            }
        }
    
        private static String getJsonResponse(InputStream res) throws IOException {
            BufferedReader rd = new BufferedReader(new InputStreamReader(res, Charset.forName("UTF-8")));
                /*TODO in java 8+ use this and avoid using the external library
                    return rd.lines().collect(Collectors.joining());
                 */
            return IOUtils.toString(rd);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2015-11-12
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多