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.
From my experience, the
tokenProperties
missing in response means googleapis.com failed to read your POST data.For your case, firstly the expected content type should be json:
If changing the above doesn't resolve the issue, then try to change the post data from object/dict/json to string too.
tips: in general, when we can't get expected response in our code, we can try experimenting the target request in straight forward tool like curl or jmeter to figure out what's wrong, then replicate the solution back into our code.