I’m currently building a small REST API with the WP-REST v2 plugin. Everything is working perfectly fine, however, in the documentation there are permission callbacks, which restrict access to certain user groups (exactly what I’m trying to do). The syntax provided is as follows:

'permission_callback' => function () {
    return current_user_can( 'edit_others_posts' );
}

The issue I’m having is that at the point of execution the current user is empty, despite being logged in and authenticated as an administrative account (session tokens exist in the cookies before, during and after the request). I figured that it may be because the route endpoint returns a page with nothing but the response text, so I tried calling the API from the index.php and wp_get_current_user();returns an empty user object and therefore current_user_can('condition') will never succeed.

Thanks for any help!

1
1

The issue was because I wasn’t generating and sending a nonce value with the request. In order to generate a nonce value. Localize the value of a wp_create_nonce('wp_rest') function call.

wp_localize_script('application', 'api', array(
    'root' => esc_url_raw(rest_url()),
    'nonce' => wp_create_nonce('wp_rest')
));

This will then be accessible to the window object of the browser which can be accessed via Javascript, this nonce should then be passed as the value of the request header X-WP-Nonce when executing XHR / HTTP Requests. An example of which is as follows:

var request = new XMLHttpRequest();

request.addEventListener('load', function() {
    console.log(this.responseText);
}

request.open('GET', api.root + 'mynamespace/posts');

// You must set headers after the request has been opened and before itself.
request.setRequestHeader('X-WP-Nonce`, api.nonce);

request.send(); // will fire the event listener above when fulfilled.

I hope this was helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *