Google's new reCaptcha site verification retur

2019-04-11 06:01发布

问题:

I do site verification after getting g-recaptcha-response thru user verification.

I send xhr POST with parameters and get 200 OK, yet NO response as it should be:

{
  "success": true|false,
  "error-codes": [...]   // optional
}

Code

<script type='text/javascript'>    
var onReturnCallback = function(response) { 
document.getElementById('resp').innerHTML = response; // works well
//alert('grecaptcha.getResponse() = ' + grecaptcha.getResponse()); // works well too
$.post("https://www.google.com/recaptcha/api/siteverify", 
          { secret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            response: response,
            remoteip :  "<?php echo $ip;?>" // optional, does not influence an empty result           
           }).complete(function( data ) {
                alert( "Data returned from POST: " + data.toString() );
                console.dir(data);
              });  

};
</script>
Form.  
<form method="post"> 
<div class="g-recaptcha" data-sitekey="6LdYKQkTAAAAAD9K6-kHspFUPUnftw1RxP5_awi0" data-callback="onReturnCallback" data-theme="light">       </div>
<input name="send" type="submit" />
</form>

The object that I print in console is totally empty (except for statusText='error'), see the shot.

There is other error in console:

XMLHttpRequest cannot load https://www.google.com/recaptcha/api/siteverify. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://tarex.ru' is therefore not allowed access.

How to deal with it? Can i change the origin header? How to verify?

The link to the demo.

回答1:

It is not possible to make XHRs ("AJAX requests") to hosts other than the one serving a website due to the so-called "same origin policy" (SOP) to prevent XSS attacks.

However you can post to the reCaptcha site from a php proxy, that you run on your own host. An example for this is given in this answer. This also prevents your secret from being public to people looking at your client-side source code.

Another possibility (depending on the service you want to use) is JSONP. As XHRs are prohibited, but loading scripts from foreign hosts is not, it is possible to add the name of a callback function via query parameters to the script URL. This function is then invoked as soon as the foreign resource is loaded. But as far as I know reCaptcha does not support JSONP.



回答2:

reCaptcha purportedly supports jsonp as a legal value of the dataType parameter.