Alex-Programer

Alex-Programer

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

Integrating Google reCAPTCHA v2

Get API key#

First, you need to go to https://www.google.com/recaptcha/admin/create to create a configuration for the website with a Version 2 "I'm not a robot" checkbox. After creating it, we will get two keys.

image.png

The site key is used for verification initiated by the client. The communication key below is used for Verifying the user's response on the server.

Client#

Structure and simple style of the control#

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

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

The style can be adjusted according to the needs of the page.

Script#

Before writing the JavaScript, you need to load a resource.

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

Then you can write the code.

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

  grecaptcha.render("robot", {
    sitekey: "Site Key",
    callback: function (token) {
      // Verification passed
    },
  });
};

When the googleVerify method is called, it will render the control on the page using the render method. When the verification is passed, the callback will be executed and a token will be passed back. To implement a comprehensive security protection, you need to pass it to the backend for final verification.

Server#

Referring to https://developers.google.com/recaptcha/docs/verify?hl=en#api_request, you can see that the server needs to send a verification request using the Google reCAPTCHA API. Taking Express middleware as an example, the specific process is as follows:

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=${Communication Key}&response=${token}`,
  });

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

This completes a complete verification process.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.