I'm trying to integrate reCAPTCHA enterprise into my Flask web application on the login page.
Initially, I added the reCAPTCHA checkbox to the login page and retrieve the token via the POST request "g-recaptcha-reponse" parameter as detailed in the documentations.
However, I keep getting an error when checking that the token is valid that says "MALFORMED" from the assessment response object as seen below...
# main Python code to get the token from the post request
recaptchaToken = request.form.get("g-recaptcha-response")
# response from Google using google-cloud-recaptcha-enterprise Python library
# action name: "projects/<project_id>/assessments/<action_id>" # Note that I hid the project_id and action_id for this question
# event {
# token: "AW-bC4mm022xpjWh2zI7od65_YdX81M6XfBPW5wIJtr8s5XXIzZ6ojfTFl9PjRlDHo601Svqpuyn5E8WhDlcBswXnrPGDbtUHekXcw60deyb8w0wyk1gZA0mJ0Hx9eAhGMI"
# site_key: "6LfpqZcgAAAAAC7RH7qroayHutXeXkpLuKY5iV6a"
# }
# token_properties {
# invalid_reason: MALFORMED
# create_time {
# }
# }
I then decided to look for other solutions such as appending the token data to the form after grecaptcha.enterprise.execute and submit the form data to the backend but I got another error in the console as shown below...
// js code
grecaptcha.enterprise.ready(function() {
grecaptcha.enterprise.execute("6LfpqZcgAAAAAC7RH7qroayHutXeXkpLuKY5iV6a", {action: "login"}).then(function(token) {
console.log(token);
});
});
// Error in console
// Uncaught (in promise) Error: Invalid site key or not loaded in api.js: 6LfpqZcgAAAAAC7RH7qroayHutXeXkpLuKY5iV6a
// at Array.<anonymous> (recaptcha__en.js:113:393)
// at recaptcha__en.js:62:400
Furthermore, for some reason, I had to wrap my site key with quotations for the reCAPTCHA Enterprise javascript src link to avoid the "Bad Request 400" error that I get from Google.
<script src="https://www.google.com/recaptcha/enterprise.js?render='6LfpqZcgAAAAAC7RH7qroayHutXeXkpLuKY5iV6a'"></script>
Left with no ideas to solve the errors, here I am on StackOverflow...
Edit #1: Looks like the malformed token is caused by enabling Web Application Firewall (WAF) Action Token during the creation of the reCAPTCHA Enterprise key...
Edit #2: This only happens if you've enabled the checkbox feature, after disabling it on a new key, everything works now!
Final edit: So when reading the documentation, only at the bottom of the page is where I realised you do not create an assessment when using WAF action-tokens or session-tokens. Hence, this error only happens if you've enabled WAF action-tokens or session-tokens as it requires you to attach the token to the request header. More details here.