This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How To Set up and Use WordPress REST API: Basic Authentication

Updated on December 10, 2021

7 Min Read
wordpress rest api

In the previous installments of this series, I have covered the introduction of WordPress REST API and Fetch Posts in WordPress REST API.

In this installment of the series on WordPress REST API, I will discuss how to set up basic authentication protocol(s) on the server so that REST API can be set up and maintain secure communication with various entities and channels.

However, I will start this tutorial with some theoretical discussion on the definition of authentication.

What Is Authentication?

In the context of Information and Communications Technology (ICT), authentication is the idea and process of verifying the credentials of the person or entity that asks for access to a particular system.

It is essential to understand that authentication is different from authorization. When a person is authenticated on a particular WordPress web Hosting server, they are granted general level access to the system. In contrast, when a person is authorized, they can access and utilize part or complete resources of the system. In other words, authentication confirms the identity while authorization identifies and grants access to the system’s resources.

In the particular context of WordPress REST API, an authenticated user can carry out CRUD tasks. However, the user must prove their authentication privileges at every step.

Managed WordPress Hosting Starting From $10/Month

Experience the fastest hosting and enjoy quick 1-click solutions. Highly secure & reliable.

Authentication With the WordPress REST API

The WordPress REST API offers several options for authentication, each intended for a specific purpose.

  • Basic Authentication
  • OAuth Authentication
  • Cookie Authentication

The native WordPress authentication manner for users and their activities is currently verified by cookies.

To use OAuth authentication and Basic Authentication with WordPress REST API, you must install the particular plugins available on the GitHub WordPress REST API group. I hope that these two methods will receive native support in the subsequent versions of WordPress REST API.

Basic Authentication

Basic authentication refers to the basic type of HTTP authentication in which login credentials are sent along with the request’s headers.

How Does Basic Authentication Work?

In Basic Authentication, the client requests a URL that requires verification. The server, in turn, requests the client to identify itself by sending a 401 Not Authorized code. In reply, the client sends the same request with the credentials (in the username:password pair) appended as a base64 encoded string. This string is sent in the Authorization header field like the following:

Authorization: Basic b3dhaXMuYWxhbUBjbG91ZHdheXMuY29tOmVKNWtuU24zNVc=

Since base64 strings could be decoded without much effort, this authentication method is not very secure. Thus, these methods should only be used in scenarios where there is absolute trust between the server and the client. Another important application of this method is troubleshooting within a secure system.

Install WordPress REST API Plugin

WordPress REST API plugin allows you to add Basic Authentication to a WordPress site.

Note:This plugin requires sending your username and password with every request and should only be used over SSL-secured connections or for local development and testing. Without SSL, we strongly recommend using the OAuth 1.0a authentication handler in production environments.”

WordPress REST API plugin is available from the GitHub WordPress REST API group. To utilize the plugin, clone it in the WordPress Plugin directory and activate it through the WordPress admin.

Send Authenticated Requests Using Postman

To start sending authentication requests, install the Postman Chrome Extension. It makes API development easier, faster, smarter, and better. For Firefox users, install  REST Easy Add-On that provides a full-featured REST client in the browser.

Postman for Chrome supports natively sending requests using the basic authentication method like most HTTP clients.

To send an authenticated request, go to the Authorization tab below the address bar:

Authenticated Request


Now select Basic Auth from the drop-down menu. You will be asked to enter your username and password. Next, click the Update request button.

Basic Auth

After updating the authentication option, you will see a change in the Headers tab. The tab will now include a header field for encoded username/password string:

Update Authentication

The setup for basic authentication with Postman is now complete. Now, send a test request (try deleting a post) which requires authentication:

For Example – DELETE

Where can be replaced with the path of your development server.

The server will return a 200 OK status if everything goes well. The status indicates that the post with the id 50 has been deleted.

OK Status

Send Authenticated Requests Using JavaScript

JavaScript is a high-level interpreted programming language, and that’s why these days, JavaScript can be found almost everywhere. Thus, it is very common to see popular JavaScript frameworks interacting with WordPress. A popular scenario is the usage of jQuery interacting with the WordPress API. In such cases, authorization headers could send in an AJAX request.

Consider the following DELETE request sent through jQuery.ajax() method:

   url: '',
   method: 'DELETE',
   crossDomain: true,
   beforeSend: function ( xhr ) {
       xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'username:password' ) );
   success: function( data, txtStatus, xhr ) {
       console.log( data );
       console.log( xhr.status );

Where Base64 is an object used for encoding and decoding a base64 string, this is defined as follows, just above  jQuery.ajax() method call:

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};

In the above request, I have set the Authorization header using the setRequestHeader() for the xhr object passed as an argument to the beforeSend() method.

In addition to the above request, the Access-Control-Allow-Headers headers should allow the Authorization field on the server. This can be enabled by adding the following line to the WordPress .htaccess file:

Header always set Access-Control-Allow-Headers Authorization Header always set

The above request, when completed, will echo out the response in the browser’s console.

200 Notification

The 200 status response code returned by the server shows that the post with the id of 52 has been deleted successfully.

Send Authenticated Requests Using WordPress HTTP API

On the off chance that you are connecting remotely with another WordPress website, the most suitable approach is to send HTTP requests through the WordPress HTTP API.

Consider the following code that sends a DELETE request to another WordPress installation with WordPress REST API and basic authentication enabled:

$wp_request_headers = array(
  'Authorization' => 'Basic ' . base64_encode( 'username:password' )

$wp_request_url = '';

$wp_delete_post_response = wp_remote_request(
      'method'    => 'DELETE',
      'headers'   => $wp_request_headers

echo wp_remote_retrieve_response_code( $wp_delete_post_response ) . ' ' . wp_remote_retrieve_response_message( $wp_delete_post_response );

Here, I have used  wp_remote_request() that accepts two arguments; $url (the URL of the request) and $args (the array that contains additional arguments to be passed).

The $method defined in the $args array is DELETE. The $headers array contains all the header fields to be passed with the request. I have passed the authorization key with a base64 encoded username and password key string.

The response would be saved in the $wp_delete_post_response variable, which could be used with the wp_remote_retrieve_response_code() and wp_remote_retrieve_response_message() functions. These two functions are helper functions in the WordPress HTTP API, and they extract the status code and the status message from the response respectively.

If the post is deleted successfully through the above request, the following text will be echoed out:

200 OK

Cookie authentication is the basic authentication method available in  WordPress. The correct cookies are set up once there is a successful login to the WordPress dashboard. Thus, the developers only have to log in for authentication.

However, the REST API incorporates nonces to deal with CSRF issues. This ensures that all activities on the website remain segregated. However, this also requires careful handling of the API.

For developers utilizing the worked as part of Javascript API, this is naturally taken care of. This is the prescribed approach to use the API for plugins and themes. Custom data models can stretch out wp.api.models.Base to guarantee this is sent correctly for any custom requests.

Developers making manual AJAX calls must pass nonce with every request. The API utilizes nonces with the activity set to wp_rest. These can then be given to the API through the _wpnonce data parameter (either POST data or the query for GET requests) or the X-WP-Nonce header.

Note: Until recently, many software had sketchy support for DELETE requests. For instance, PHP does not transform the request body of a DELETE request into a superglobal. Supplying the nonce as a header is the most reliable approach in this scenario.

It is important to remember that this confirmation strategy depends on WordPress cookies. Thus, this method is only relevant when the REST API is utilized within WordPress and the current user is logged in. Moreover, the current user must have appropriate authorization for the activity being performed.

As an example, this is how the built-in JavaScript client creates nonce:

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

Here is an example of editing the title of a post using jQuery AJAX:

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

Final Thoughts

WordPress REST API is perhaps the most popular and extensively used REST API globally. It is available to everyone who uses WordPress for online stores and web apps.

I hope you have understood whatever I have written in this article. If you still have a question about the topic or would like to contribute to the discussion, please leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Beautifully optimized hosting for WordPress and Magento”

Arda Burak [Agency Owner]

Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]


Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!


Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!