pythongcloudrecaptcha-enterprise

gcloud recaptcha enterprise - creating an assessment


I am working through the ReCaptcha Enterprise tutorial and have gotten stuck with a 400 Request contains an invalid argument error. I am using Django.

I am following the instructions here https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#python to authenticate the recaptcha.

I have been able to load the recaptcha on the front-end with this code

{% block content %}
<script type="text/javascript">
  var onloadCallback = function() {
    grecaptcha.enterprise.render('html_element', {
      'sitekey' : '{{ sitekey }}',
    });
  };
</script>
<form action="{% url 'captcha-authentication' %}" method="post">
  {% csrf_token %}
  <div id="html_element"></div>
  <input type="submit" value="Submit">
</form>

<script src="https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&render=explicit"
async defer>
</script>

I have verified in my view that request.POST contains the 'g-recaptcha-response' key. For my site_key, I am using the key id from https://console.cloud.google.com/security/recaptcha.

def confirm_captcha(token, site_key, recaptcha_action):
  parent_project = "t-commerce-321516"

  client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

  event = recaptchaenterprise_v1.Event()
  event.site_key = site_key
  event.token = token
  event.expected_action = recaptcha_action

  assessment = recaptchaenterprise_v1.Assessment()
  assessment.event = event

  request = recaptchaenterprise_v1.CreateAssessmentRequest()
  request.assessment = assessment
  request.parent = parent_project

  # this is the line that is throwing an error
  response = client.create_assessment(request)

  if not response.token_properties.valid:
    print("The CreateAssessment() call failed because the token was " +
          "invalid for the following reasons: "
          + str(response.token_properties.invalid_reason))
  else:
    if response.event.expected_action == recaptcha_action:
      print("The reCAPTCHA score for this token is: " +
            str(response.risk_analysis.score))
      return True
    else:
      print("The action attribute in your reCAPTCHA tag does" +
            "not match the action you are expecting to score")

  return False

The error from creating the client assessment is 400 Request contains an invalid argument.

Is there a way to tell why Google is angry?

I am using a checkbox on the front-end and maybe that means that the recaptcha_action argument isn't needed, but I'm not sure how to do that.

Any help or pointers is appreciated!


Solution

  • I think you need:

    request.parent = `projects/${parent_project}`
    

    per: CreateAssessmentRequest