How does REST API cookie authentication work in WP 4.7?

It looks like you’re missing the nonce part, as explained in the Authentication chapter, in the REST API Handbook:

Cookie authentication is the basic authentication method included with
WordPress. When you log in to your dashboard, this sets up the cookies
correctly for you, so plugin and theme developers need only to have a
logged-in user.

However, the REST API includes a technique called nonces to avoid CSRF
issues. This prevents other sites from forcing you to perform actions
without explicitly intending to do so. This requires slightly special
handling for the API.

For developers using the built-in Javascript API, this is handled
automatically for you. This is the recommended way to use the API for
plugins and themes. Custom data models can extend wp.api.models.Base
to ensure this is sent correctly for any custom requests.

For developers making manual Ajax requests, the nonce will need to be
passed with each request. The API uses nonces with the action set to
wp_rest. These can then be passed to the API via the _wpnonce data
parameter (either POST data or in the query for GET requests), or via
the X-WP-Nonce header.

Based on the Backbone JavaScript Client chapter, we can use the core wp-api REST API Backbone client library.

Here’s your modified snippet in a /js/test.js script file in the current theme directory:

wp.api.loadPromise.done( function() {

  // Create a new post
  var post = new wp.api.models.Post(
      {
        title: 'Posted via REST API',
        content: 'Lorem Ipsum ... ',
        status: 'draft',  // 'draft' is default, 'publish' to publish it
    }
  );

  var xhr = post.save( null, {
     success: function(model, response, options) {
       console.log(response);
     },
     error: function(model, response, options) {
       console.log(response);
     }
   });

});

where we enqueue the wp-api client library and our test script with:

add_action( 'wp_enqueue_scripts', function()
{
    wp_enqueue_script( 'wp-api' );
    wp_enqueue_script( 'test_script', get_theme_file_uri( '/js/test.js' ), [ 'wp-api' ] );

} );

within functions.php file in the current theme.

Note that this test script just creates a new post draft, during each page load on the front-end, for a logged in user with the capability to create new posts.

Leave a Comment