I have an app which is should be secure and therefore using Nonce's but I can't get them to work. I have tried several options but apparently something is missing as the validation doesn't work.
My js code fragment is:
function placeNew(next){
_nonce = $('input#_nonce').val();
request = $.ajax({
type: 'POST',
url: url_path + '/foo/v1/newbee',
data: {bid : next , _nonce : _nonce},
security: '<?php echo wp_create_nonce( "a" ); ?>',
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
str = JSON.stringify(response);
if(response["error"]){
alert(response["message"]);
}
The nonce is added to the page with the following code:
$nonce = wp_create_nonce( 'a' );
echo "<input type='hidden' id='_nonce' value=" . $nonce ."/>";
Within php the following function fragment is used to get and compare the nonce:
function ace($request) {
global $wpdb;
$timestamp = time();
$nonce = (string) $request['_nonce'];
$verify = check_ajax_referer( 'a', $nonce, false );
if ( ! $verify){
$errMsg = $nonce . '-'. $verify .' not validated ';
return (object) array(error => true, message => $errMsg);
}
I always do get the message "not validated". $nonce has a value but $verify never gets a value.
According to the docs:
The important part you are missing is:
For it to work, you must name your action in the
wp_create_nonce
towp_rest
.So for your code, you must change all instances of:
to
Also, as the docs state:
So adding this to your ajax is simple and looks something like:
Also, to fix the check
Should now be