I created a ReCaptcha Enterprise project for my frontend and am trying to verify assessments in an AWS Lambda.
The ReCaptcha project looks as follows: ReCaptcha Settings
The front end code is a react application but I am just using scripts following the documentation. This all seems to work. I can solve the captcha and get the answer.
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" />
);
So next is the lambda which is called as a trigger from 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");
}
};
This is the response I always get.
{
"name": "projects/<PROJECT>/assessments/924d7fc3f0000000",
"score": 0,
"reasons": []
}
However the recaptcha dashboard shows that all have the assessments have been >= 0.8 I have no idea what I am doing wrong. thank you for any help.