如何在 Node.js 服务器调用中验证 recaptcha?
Google reCAPTCHA: reCAPTCHA 是一个 CAPTCHA 系统,它使网络主机能够区分人工访问和自动访问网站。该服务由谷歌提供。
google 提供了两个版本的 reCAPTCHA:
- 验证码 v3
- 验证码 v2
在本文中,我们将了解 reCAPTCHA v2。
方法:
- 在 google reCAPTCHA 上注册您的网站
- 提交 HTML 表单。
- 在 Node.js 服务器中获取响应密钥
- 重新验证密钥并响应用户端。
第 1 步:在 google reCAPTCHA 上注册您的网站
在 Google reCAPTCHA 平台上注册您的网站以获取密钥,即编码 HTML 表单所需的站点密钥和密钥。
单击此处转到 Google reCAPTCHA 网站。
第 2 步:在 HTML 中创建 Google reCAPTCHA 表单
在这里,我们将创建一个简单的 HTML 表单,其动作为 /submit、一个输入字段和一个按钮。同时,我们需要在我们的 HTML 文档中添加 google reCAPTCHA CDN,并在表单中添加一个 div 标签,以便在 HTML 文档中获取 reCAPTCHA。
CDN:
DIV TAG:
注意:您需要将“your_site_key”替换为您的站点密钥。
例子:
文件名:index.html
HTML
Google recaptcha
CSS
.container {
border: 1px solid rgb(73, 72, 72);
border-radius: 10px;
margin: auto;
padding: 10px;
text-align: center;
}
h1 {
margin-top: 10px;
}
input[type="text"] {
padding: 10px;
border-radius: 5px;
margin: 10px;
font-family: "Times New Roman", Times, serif;
font-size: larger;
}
button {
border-radius: 5px;
padding: 10px;
color: #fff;
background-color: #167deb;
border-color: #0062cc;
font-weight: bolder;
cursor: pointer;
}
button:hover {
text-decoration: none;
background-color: #0069d9;
border-color: #0062cc;
}
.g-recaptcha {
margin-left: 513px;
}
Javascript
{
"name": "google_recaptcha",
"version": "1.0.0",
"description": "Google recaptacha v2 demonstration.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "Asmit Sirohi",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"isomorphic-fetch": "^3.0.0"
}
}
Javascript
// Importing express package
const express = require("express");
// Importing isomorphic-fetch package
const fetch = require("isomorphic-fetch");
// instantiating express package
const app = express();
// Making public folder static where index.html file is present
// By making it static, we can easily serve index.html page
app.use(express.static("public"));
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
// Here, HTML form is submit
app.post("/submit", (req, res) => {
const name = req.body.name;
// getting site key from client side
const response_key = req.body["g-recaptcha-response"];
// Put secret key here, which we get from google console
const secret_key = "";
// Hitting POST request to the URL, Google will
// respond with success or error scenario.
const url =
`https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
// Making POST request to verify captcha
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
// google_response is the object return by
// google as a response
if (google_response.success == true) {
// if captcha is verified
return res.send({ response: "Successful" });
} else {
// if captcha is not verified
return res.send({ response: "Failed" });
}
})
.catch((error) => {
// Some error while verify captcha
return res.json({ error });
});
});
// lifting the app on port 4000.
const PORT = 4000;
app.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`));
文件名:style.css
CSS
.container {
border: 1px solid rgb(73, 72, 72);
border-radius: 10px;
margin: auto;
padding: 10px;
text-align: center;
}
h1 {
margin-top: 10px;
}
input[type="text"] {
padding: 10px;
border-radius: 5px;
margin: 10px;
font-family: "Times New Roman", Times, serif;
font-size: larger;
}
button {
border-radius: 5px;
padding: 10px;
color: #fff;
background-color: #167deb;
border-color: #0062cc;
font-weight: bolder;
cursor: pointer;
}
button:hover {
text-decoration: none;
background-color: #0069d9;
border-color: #0062cc;
}
.g-recaptcha {
margin-left: 513px;
}
输出:
第 3 步:Node.js 服务器:
我们已经准备好表单,让我们编写我们的服务器文件。在服务器端,我们将使用两个包,一个是 express 用于服务器作为 web 框架,另一个是 isomorphic-fetch 用于 http/https 调用。
创建新目录并在其中生成 package.json 文件。使用npm init命令生成 package.json 文件,这是最佳实践。这是我的 package.json 文件供参考。
文件名:package.json
Javascript
{
"name": "google_recaptcha",
"version": "1.0.0",
"description": "Google recaptacha v2 demonstration.",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"author": "Asmit Sirohi",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"isomorphic-fetch": "^3.0.0"
}
}
现在,让我们为 HTML 表单提交数据的服务器文件编写代码。
第 4 步:验证验证码:
为了验证验证码,我们需要向以下 URL 发出 post 请求。
- 网址: https://www.google.com/recaptcha/api/siteverify?secret=
&response= - secret_key :您将从谷歌控制台获得此密钥,即密钥。
- response_key:当用户提交表单时,这个key来自客户端。
笔记:
- g-recaptcha-response 是浏览器在表单提交时生成的响应键的名称。如果它的空白或 null 表示用户没有选择验证码,则返回错误。
- 您需要将“your_secret_key”替换为您的密钥。
文件名:app.js
Javascript
// Importing express package
const express = require("express");
// Importing isomorphic-fetch package
const fetch = require("isomorphic-fetch");
// instantiating express package
const app = express();
// Making public folder static where index.html file is present
// By making it static, we can easily serve index.html page
app.use(express.static("public"));
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
// Here, HTML form is submit
app.post("/submit", (req, res) => {
const name = req.body.name;
// getting site key from client side
const response_key = req.body["g-recaptcha-response"];
// Put secret key here, which we get from google console
const secret_key = "";
// Hitting POST request to the URL, Google will
// respond with success or error scenario.
const url =
`https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
// Making POST request to verify captcha
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
// google_response is the object return by
// google as a response
if (google_response.success == true) {
// if captcha is verified
return res.send({ response: "Successful" });
} else {
// if captcha is not verified
return res.send({ response: "Failed" });
}
})
.catch((error) => {
// Some error while verify captcha
return res.json({ error });
});
});
// lifting the app on port 4000.
const PORT = 4000;
app.listen(PORT, () => console.log(`Server is running on PORT ${PORT}`));
运行应用程序:
要运行应用程序,请切换到项目文件夹并使用命令运行 Node 应用程序。
node app.js
转到 localhost:4000 以查看该应用程序。
输出:
- 当验证码验证时
- 当验证码未验证时