Alex-Programer

Alex-Programer

随缘博客,不定期更新不确定的内容~
github
twitter

Google reCAPTCHA v2 接入

获取 API key#

首先需要前往 https://www.google.com/recaptcha/admin/create ,为网站创建一个第 2 版 “进行人机身份验证” 复选框的 配置。创建完成后,我们会得到两个密钥。

image.png

网站密钥,是在客户端发起验证使用的。而下面的通信密钥,则是为了在服务端做 Verifying the user's response 用的。

客户端#

控件的结构与简单样式#

<div id="robot"></div>
#robot {
  position: fixed;
  left: 50%;
  transform: translate(-50%, 0);
  bottom: 270px;
}

@media screen and (max-width: 768px) {
  #robot {
    bottom: 200px;
  }
}

样式可以自行根据页面需要来调整

脚本#

在编写 js 之前,需要先加载一个资源进来。

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

之后就可以编写代码了

export const googleVerify = () => {
  if (!grecaptcha.render) return;

  grecaptcha.render("robot", {
    sitekey: "网站密钥",
    callback: function (token) {
      // 验证通过
    },
  });
};

googleVerify 方法被调用时,它会通过 render 方法渲染控件到页面上。当验证通过时,callback 会被执行,并回传一个 token 过来,要做好一个完备的安全防护,就需要把它传递给后端,做最后的验证。

服务端#

参考 https://developers.google.com/recaptcha/docs/verify?hl=en#api_request 即可知道,服务端要做的就是使用 Google reCAPTCHA 的一个 API 发送验证请求。以 Express 的中间件为例,具体处理过程为:

const verifyGoogleToken: RequestHandler = async (req, res, next) => {
  const { token } = req.body;

  const { data } = await axios({
    url: "https://www.google.com/recaptcha/api/siteverify",
    method: "post",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    data: `secret=${通信密钥}&response=${token}`,
  });

  if (data && data.success) {
    next();
  } else {
    res.send("google verify failed");
  }
};

这样一个完整的验证过程就完成了。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。