关于vue.js:Vue-项目中使用-reCAPTCHA-人机验证服务

8次阅读

共计 1587 个字符,预计需要花费 4 分钟才能阅读完成。

在前段时间的训练中,我偶尔接触到谷歌提供的收费人机验证服务 reCAPTCHA,在一番学习后已将它接入到我的 Vue 练习我的项目中。上面将介绍我的接入过程与踩过的坑。

reCAPTCHA v2

首先,你须要在 ./public/index.html 中增加上面这段代码:

<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>

这里须要阐明一下,在中国请用 www.recaptcha.net 替换 www.google.com

<script src="https://www.recaptcha.net/recaptcha/api.js?render=explicit" async defer></script>

点击复选框来验证

创立一个 vue 组件,残缺代码如下:

<template>
  <!-- 增加一个 div 用作容器 -->
  <div id="grecaptcha"></div>
</template>
<script>
export default {data() {
    return {sitekey: "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"};
  },
  methods: {submit: function(token) {console.log(token);
    },
    loaded() {setTimeout(() => {
        window.grecaptcha.render("grecaptcha", {
          sitekey: this.sitekey,
          callback: this.submit
        });
      }, 200);
    }
  },
  mounted() {this.loaded();
  }
};
</script>

阐明:

data() {
 return {sitekey: "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"}
},

sitekey 测试专用 key,你须要注册一个本人的 sitekey 用在生产环境中。

注册地址(迷信上网):https://www.google.com/recaptcha/admin/create

注册胜利后失去两个密钥:

第一个密钥即是 sitekey

setTimeout(() => {
        window.grecaptcha.render("grecaptcha", {
          sitekey: this.sitekey,
          callback: this.submit
        });
}, 200);

grecaptcha 的渲染 API,延时 200ms 防止报以下谬误:

this.submit 为回调函数,接管返回的 token 用于后端验证。

除了 sitekeycallback 外,还有其余的参数,具体请看:这里

将接管到的 token 传到后端即可。

      this.axios
        .get("http://localhost:3000/login", {
          params: {token: token}
        })
        .then(function(response) {console.log(response);
        })
        .catch(function(error) {console.log(error);
        });

后端验证

let res = await axios
.get("https://recaptcha.net/recaptcha/api/siteverify", {
  params: {
    secret: "6LdFp74UXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXX",
    response: ctx.query.token
  }
});
ctx.body = res.data;

参数:

  • secret 为失去的第二个密钥
  • response 为接管到的 token

返回:

失去 success: true 示意通过验证。

(写于 2019 年 11 月)

正文完
 0