June 29, 2023

Handling User Authentication in the WordPress REST API: Sending POST Requests with Cookie Authentication

This article explains how to handle user authentication in the WordPress REST API, with a focus on the simplest method: Cookie Authentication. It also demonstrates how to use wp_nonce tokens to validate POST requests and avoid common HTTP 403 unauthorized errors. You’ll find practical code examples for generating a nonce cookie and adding it to your POST requests. This is especially helpful when working with frontend frameworks or making POST requests from the backend.


WordPress REST API Authentication Methods

WordPress supports three main authentication methods for its REST API:

  • Cookie Authentication (for logged-in users)
  • OAuth Authentication
  • Basic HTTP Authentication

When you’re using the REST API to fetch public data (via GET requests), no authentication is needed. However, when sending data via POST, PUT, or DELETE, authentication is required—otherwise, you’ll get an HTTP 403 unauthorized error.

This tutorial focuses on the most straightforward method: Cookie Authentication using nonces.


How Cookie Authentication Works

The key idea is to use nonces (numbers used once) generated by WordPress to ensure that the request is coming from a trusted source (i.e., your WordPress site) and not an external client. WordPress will verify the nonce with each POST request.


Step 1: Generate and Pass a Nonce to JavaScript

Add the following code to your functions.php file or relevant plugin file to enqueue your script and pass the nonce to your JavaScript:

function enqueue_scripts_styles_init() {
    wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri() . '/js/script.js', array( 'jquery' ), '1.0', true );
    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' );

Now, in your JavaScript, you can access WP_API_Settings.nonce and WP_API_Settings.root.


Step 2: Add the Nonce to Your POST Request

Here’s an example using the Mithril.js framework to send a POST request with authentication:

// Add nonce to the request header
var xhrConfig = function (xhr) {
    xhr.setRequestHeader("X-WP-Nonce", WP_API_Settings.nonce);
};

// Mithril model and logic
var posts_add = {
    getData: function () {
        return {
            title: m.prop(""),
            content: m.prop(""),
            saved: m.prop(false),
            error: m.prop("")
        };
    },

    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);
    }
};

This snippet ensures that the X-WP-Nonce header is included in the request, which WordPress verifies before processing the POST.


Notes for Other Frameworks and Backends

The same authentication principle applies if you’re using other JavaScript frameworks like Vue, React, or Angular—or even making requests from the backend with curl or Postman.

  • Always include the X-WP-Nonce header in your request.
  • Ensure the nonce was generated by wp_create_nonce('wp_rest') on the server side.

Conclusion

If you’re building a custom front-end or working with AJAX POST requests in WordPress, Cookie Authentication with nonces offers a quick and secure method for authentication. While OAuth and Basic Auth are useful for external applications and mobile apps, nonce-based authentication is perfect for logged-in users interacting with your own WordPress site.

Make sure to read the official REST API documentation for updates and best practices.