我为我的前端创建了一个 ReCaptcha Enterprise 项目,并试图在 AWS Lambda 中验证评估。
ReCaptcha 项目如下所示:ReCaptcha 设置
前端代码是一个反应应用程序,但我只是使用文档之后的脚本。这一切似乎都奏效了。我可以解决验证码并得到答案。
const [captchaAnswer, setCaptchaAnswer] = useState<string | null>(null);
useEffect(() => {
const script = document.createElement('script');
script.src = "https://www.google.com/recaptcha/enterprise.js";
script.async = true;
script.defer = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
window.reCaptchaCallback = function (response: string) {
setCaptchaAnswer(response);
};
const submit = () => {
//Submits the answer to my lambda
}
return (
<div className="g-recaptcha" data-sitekey="<SITEKEY>" data-callback="reCaptchaCallback" />
);
所以接下来是 lambda,它被称为 Cognito 的触发器。
const axios = require("axios");
const config = {
PROJECT_ID: "<PROJECTID>",
API_KEY: "<APIKEY>", //actually gotten from secret manager
SITE_KEY:"<SITEKEY>"
};
exports.handler = async (event) => {
console.log(event);
if (event.triggerSource === "PreSignUp_AdminCreateUser") {
return event;
}
if (!event.request.validationData) {
throw new Error('Missing validation data');
}
try {
const verifyResponse = await axios({
method: 'post',
url: `https://recaptchaenterprise.googleapis.com/v1beta1/projects/${config.PROJECT_ID}/assessments?key=${config.API_KEY}`,
body: {
event: {
token: event.request.validationData.token, //I have confirmed this is correctly passed from front end to here
siteKey: config.SITE_KEY
expectedAction: "" //Tried it with and without this. Documentation say it isn't being used
}
},
headers: { "Content-Type": "application/x-www-form-urlencoded" }
});
console.log(JSON.stringify(verifyResponse.data));
if (verifyResponse.data.score >= 0) {
event.response.autoConfirmUser = true;
return event;
} else {
throw new Error('Recaptcha verification failed');
}
} catch (error) {
console.error(error);
throw new Error("Recaptcha verification failed. Please retry");
}
};
这是我总是得到的回应。
{
"name": "projects/<PROJECT>/assessments/924d7fc3f0000000",
"score": 0,
"reasons": []
}
然而,recaptcha 仪表板显示所有的评估都 >= 0.8 我不知道我做错了什么。感谢您的任何帮助。