WP-API and Basic Auth returning 403 on POST but not GET

I am using the latest, WP-API and the recommended Basic Auth, to test adding a post to WP from remote.

I have Access Headers opened up on the WP side:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");
header("Access-Control-Allow-Headers: Authorization, Content-Type");

When I submit a Get request to: http://sandbox.ravennainteractive.com/wp-json/wp/v2/posts the call easily authenticates and returns the Hello World Post.

When I submit a Post request to the same url. I get an error. Here is my jquery ajax call:

$('#test-post').submit(function(e){
    e.preventDefault();

    var title = $( '#title' ).val();
    var content = $( '#content_raw' ).val();

    var postData = {
        title: title,
        content: content
    }

    console.log(postData);

    $.ajax({
        method: 'POST',
        contentType: 'application/json',
        data: postData,
        url: sandboxUrl,
        beforeSend: function( xhr ) {
           xhr.setRequestHeader ('Authorization', 'Basic '+ btoa( 'apiuser' + ':' + 'PASSWORD' ));
        },
        success: function(data){
            console.log(data);
            alert('Your comment was successfully added');
        },
        error: function(data){
            console.log(data);
            alert('There was an error adding your comment');
        }
    });

    return false;
});

The response is Failed to load resource: the server responded with a status of 403 (Forbidden)

Array[0]responseText: “[{“code”:”rest_forbidden”,”message”:”You don’t have permission to do this.”,”data”:{“status”:403}}]”

If run this block of code, removing unnecessary extras the query works and returns the Hello World post.

 $('#test-post').submit(function(e){
    e.preventDefault();

    $.ajax({
        method: 'GET',
        url: sandboxUrl,
        beforeSend: function( xhr ) {
           xhr.setRequestHeader ('Authorization', 'Basic '+ btoa( 'apiuser' + ':' + 'PASSWORD' ));
        },
        success: function(data){
            console.log(data);
            alert('Your comment was successfully added');
        },
        error: function(data){
            console.log(data);
            alert('There was an error adding your comment');
        }
    });

    return false;
});

How can I solve this?

1 Answer
1

I’ve met the same issue.

…the recommended Basic Auth…

I found that the problem is in the Basic Auth plugin. WP-API guys recommend using their own plugin and this solution works for me.

  1. Deactivate all activated basic auth plugins in your WordPress dashboard
  2. On the machine your WordPress is running go to the plugin folder
  3. Run

    git clone https://github.com/WP-API/Basic-Auth.git

  4. Go to your WordPress admin dashboard, plugins page. JSON Basic Authentication should be in the list. Activate it.

Now creating a record via POST request should work.

Leave a Comment