WordPress REST API Basic Authentication

WordPress REST API Basic Authentication

The WordPress REST API does not come with any type of authentication. A lot of the API endpoints do not require authentication. If you want to do things like post content or create users you will need to be authenticated or “logged in”.

If your application is on the site, loaded from the same server as the API, you can piggy back on WordPress’ auth cookies in the form of a nonce.

Setting the cookie nonce using wp_localize_script(). This function formats your nonce url to the API into JSON format so its easier to use in javascript ajax. Add the code below in your plugin or perhaps the themes functions file.

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

Then in your Application javascript (example is jQuery) you can create a post. You need to only include a post tile to create a new post.

$.ajax( {
    url: wpApiSettings.root + 'wp/v2/posts/',
    method: 'POST',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
        'title' : 'Hello Moon'
} ).done( function ( response ) {
    console.log( response );
} );


You can pass the same arguments in the data of your ajax call as you do the wp_insert_post()