6

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!

9

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.

  • I am curious about where you would add this code exactly? functions.php or in a plugin? I am struggling with a similar issue.. – anniec Sep 29 '16 at 17:18
  • Hi @anniec, the wp_localize_script function is called in functions.php and simply adds a property to the window object in the browser which can be accessed via Javascript, in the example above the wp_localize_script call adds a property to the window object called api when the script application is enqueued. The third parameter then sets the value of window.api so in the above example, window.api.root would return the escaped rest api url and window.api.nonce would return the rest api nonce. This nonce must be sent as a request header to check the current user's permissions. – connorb Sep 30 '16 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.