A Guide To WordPress REST API Authentication

WordPress provides a REST API to get, update, and delete the WordPress website data. This means that we can use WordPress CMS as a backend system to create & manage content and Angular or React to design our frontend application to consume the content using the WordPress REST API. In this blog post, we discussed the authentication process to safely and securely consume WordPress data using WordPress REST API.

What Is Authentication?

  • Authentication means verifying identity and checking if the source has the rights to access the requested data
  • Adds a layer of security
  • When a user logs in to the WordPress website, it receives an access token which is stored in a browser cookie
  • This access token is then used to authenticate the user for future requests
  • Based on the access token-based authentication WordPress decides whether the user can access the requested data or not

When Authentication Is Required?

  • To read private data
  • To create new data i.e. posts, pages, etc.
  • To update data
  • To delete data
  • In other words, any action requiring a login to the WordPress dashboard requires authentication when using REST API

Types of Authentication

  • Basic authentication: used only for development purposes with basic auth plugin. It uses only login and password to authenticate the user (never use this in production)
  • Cookie-based authentication: used when using REST API inside WordPress admin dashboard i.e using plugins or themes
  • Token-based authentication (JWT, OAuth, etc.): used when using REST API inside a standalone application

Secure Authentication

  • Perform authentication over HTTPS
  • Means that both the WordPress website and client app must have HTTPS protocol configured for secure communication

Cookie Authentication

  • WordPress uses cookies to store the session information of the user
  • That session information is stored in both the browser (cookie) and server
  • Ensures that the authenticated user has access to manipulate the requested data
  • Cookies authentication is used when the WordPress API is used to make requests from within the WordPress dashboard i.e. inside plugins or themes
  • Cookie authentication cannot be used for accessing WordPress REST API data from standalone applications
  • It prevents middleware attacks and other nefarious incursions
  • Cross-site request forgery (CSRF) is an inherent security flaw of using cookie authentication
    • It can be prevented using the nonces (number used once)
    • This nonce is assigned to the user when logged in and passed with all user requests for secure actions
    • This nonce is automatically changed after 24 hours
    • We need to implement nonces when making REST API calls because it’s not implemented automatically like the cookie authentication

Cookie Authentication Example (Front-End Post Editing Plugin)

Create a new folder inside the wp-content/plugins folder of the WordPress installation folder. Name it something like fronted-editor and inside that folder create a new file and name it frontend-editor.php. Add the following code in it:

/*
Plugin Name: Frontend Editor
Plugin URI: #
Description: Edit post title from frontend of the website
Version: 1.0
Author: Junaid Hassan
Author URI: https://codoplex.com
Text Domain: frontend-editor
*/

function restedit_scripts(){
   if(!is_admin() && is_single()){
      if(is_user_logged_in && current_user_can('edit_others_posts')){
         wp_enqueue_script('restedit_script', plugin_dir_url(__FILE__).'js/restedit.ajax.js', '1.0', 'jquery', true);
         wp_localize_script('restedit_script', 'wpsettings', array(
            'root' => esc_url_raw(rest_url()),
            'nonce' => wp_create_nonce('wp_rest'),
            'current_ID' => get_the_ID()
         ));
      }
   }
}
add_action('wp_enqueue_scripts', 'restedit_scripts')

Create a new folder named js, add a new file named restedit.ajax.js and the following code in it.

(function($){
   const $ENTRYTITLE = $('.entry-title');
   $ENTRYTITLE.after('<button class="edit-button edit-title">Edit</button><button class="save-button save-title" style="display: none">Save</button>');

   function runAjax(newTitle){
      $.ajax({
         url: wpsettings.root + 'wp/v2/posts/' + wpsettings.current_ID,
         method: 'POST',
         beforeSend: function(xhr){
            xhr.setRequestHeader('X-WP-Nonce', wpsettings.nonce);
         },
         data: {
            title: newTitle
         }
      });
   }

   $('edit-button.edit-title').click(function(){
      let $originalTitle = $ENTRYTITLE.text();
      $ENTRYTITLE.toggle();
      $ENTRYTITLE.after('<input id="title-input" type="text">');
      document.querySelector('#title-input').value = $originalTitle;
      $(this).toggle();
      $('.save-button.save-title').toggle();
   });

   $('.save-button').click(function(){
      let newTitle = document.querySelector('#input-title').value;
      $ENTRYTITLE.text(newTitle);
      $ENTRYTITLE.toggle();
      $('#input-title').toggle();
      $('.edit-button.edit-title').toggle();
      $(this).toggle();
      runAjax(newTitle);
   });
})(jQuery);

Now go into plugins and activate the plugin. Now upon visiting any post from frontend users with post-editing capability will be able to edit and save the post title from the frontend of the website.

JWT Authentication

  • Complete name is JSON web token
  • Securely communicates JSON data between the source (WordPress website) and a client (standalone application)
  • We need to add JWT authentication functionality using a plugin (e.g. JWT Authentication for WP REST API)
    • Follow the instructions on the plugin page to define the secret key (generate from here) and CORS support inside wp-config.php file
    • Also, modify the .htaccess file as suggested
    • Follow the instructions on the plugin page to learn how to get and validate access token for future API requests
  • Process steps are as follows:
    • From client app, post request is sent with username and password to the WordPress REST API
    • If username and password are matched, JWT is generated and sent back to the client app (browser)
    • Now the client can send requests to REST API along with the JWT token
    • REST API authenticates the token and if successful the response is sent back to the client

Leave a Comment

Your email address will not be published.