简体   繁体   中英

ReCaptcha Enterprise api call always returns score of 0 but the dashboard shows every score has been 0.8 or greater

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:

    "Content-Type": "application/json; charset=utf-8"

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.

this is the curl which is working for me, may be can help you. Review the body and send a assessments object including the event object inside.

curl -H 'Content-Type: application/x-www-form-urlencoded' -X POST https://recaptchaenterprise.googleapis.com/v1beta1/projects/${here-is-your-id-project}/assessments?key=${here-is-your-secret-key-defined-on-credentials-api-section} -d 'assessment.event.token=${response-token-coming-from-grecaptcha.enterprise.execute-method-on-web-site}' -d 'assessment.event.site_key=${here-is-your-public-key-defined-on-recaptcha-service-section}'

this is the response:

{
  "name": "projects/xxxx/assessments/xxxxx",
  "event": {
    "token": "${response-token-coming-from-grecaptcha.enterprise.execute-method-on-web-site}",
    "siteKey": "${here-is-your-public-key-defined-on-recaptcha-service-section}",
    "userAgent": "",
    "userIpAddress": "",
    "expectedAction": "",
    "hashedAccountId": ""
  },
  "score": 0.9,
  "tokenProperties": {
    "valid": true,
    "invalidReason": "INVALID_REASON_UNSPECIFIED",
    "hostname": "your-host-goes-here",
    "action": "login",
    "createTime": "2022-02-03T19:08:01.612Z"
  },
  "reasons": []
}

My GCP configuration:

That's all

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM