Handle User Authentication for POST Requests in the WordPress REST API

The WordPress REST API supports three main authentication methods: cookie authentication, OAuth authentication, and basic HTTP authentication. When you are only fetching public data through the API, no authentication is needed. But once you start sending data to the API with POST requests, authentication becomes necessary or the request will fail with an HTTP 403 error.

This article focuses on the simplest option: cookie authentication backed by WordPress nonces.

First, generate the nonce data with wp_create_nonce()

The idea is to generate a nonce on the server and expose it to the front end so the browser can include it in later API requests. That lets WordPress verify that the request really came from the same site.

function enqueue_scripts_styles_init() {
	wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/js/script.js', array('jquery'), 1.0 );
	wp_localize_script( 'ajax-script', 'WP_API_Settings', array( 
            'root' => esc_url_raw( rest_url() ), 
            'nonce' => wp_create_nonce( 'wp_rest' ) 
        )
    );
}
add_action('init', 'enqueue_scripts_styles_init');

Add the nonce to the POST request

Once the front end has access to the nonce, include it in the request headers for API calls that modify data.

// Request configuration
var xhrConfig = function (xhr) {
    xhr.setRequestHeader("X-WP-Nonce", WP_API_Settings.nonce);
};

// Model
var posts_add = {
    // Initialize data
    getData: function () {
        return {
            title: m.prop(""),
            content: m.prop(""),
            saved: m.prop(false),
            error: m.prop("")
        }
    },


    // Save form data
    setData: function (data) {
        return m.request({
                method: "POST",
                url: "/wp-json/wp/v2/posts/",
                config: xhrConfig,
                data: {
                    title: data.title(),
                    content: data.content()
                }
            })
            .then(data.saved.bind(this, true), data.error)
    }
};

The original code is based on Mithril, but the same authentication approach works with other front-end frameworks or even with server-side clients. The key point is always the same: include the nonce in the X-WP-Nonce header so WordPress recognizes the request as a valid same-site request.

If you need OAuth or basic HTTP authentication instead, WordPress’s official documentation covers those methods too. But for many front-end interactions inside the same site, nonce-based cookie authentication is the most straightforward option.

Related Posts

Leave a Reply

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