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.
- What Is REST API, and How Does It Work?
- What Is Basic Authentication and Why Is It Important?
- How Does Basic Authentication Work?
- Authentication Methods for WordPress Rest API
- Understanding WordPress REST API Commands
- Install WordPress REST API Plugin
- Send Authenticated Requests Using Postman
- Send Authenticated Requests Using JavaScript
- Send Authenticated Requests Using WordPress HTTP API
- Cookie Authentication
- Final Thoughts
However, I will start this tutorial with some theoretical discussion on the definition of authentication.
What Is REST API, and How Does It Work?
A REST (Representational State Transfer) API (Application Programming Interface) communicates between different software components over the Internet. It allows developers to access and manipulate data and resources from a web service like WordPress using standard HTTP methods.
For example, using Javascript, you can use a REST API to create, read, update, or delete posts and pages on a WordPress site from another application.
A REST API is based on the principle of statelessness, which means that each request from a client to a server must contain all the information needed to process the request. The server does not store any information about the client’s state or history between requests. This makes the REST API more scalable, reliable, and efficient.
What Is Basic Authentication and Why Is It Important?
Basic authentication checks who you are when you want to use a web service. It works by sending your username and password in a simple way over the internet. The web service then looks to see if your username and password are right and lets you in or not.
Basic authentication is important because it helps to keep your data and resources safe from other people who should not see or change them. If there is no authentication, anyone can see and change your data and resources, which can cause problems or harm.
However, basic authentication also has some problems and dangers. For example, it does not hide your username and password, which means that someone who can see your internet request can also see your username and password easily.
Maximize Development with WordPress Rest API
Pair it with the perfect hosting solution to ensure lightning-fast response times and unparalleled uptime.
How Does Basic Authentication Work?
Basic authentication is a simple way of verifying a client’s identity who wants to access a protected resource on a server. It works by sending the username and password of the client as part of the HTTP request.
Here are the steps involved in basic authentication:
- The client requests a URL that requires authentication, such as https://example.com/secret.
- The server responds with a 401 Unauthorized Error and a WWW-Authenticate header that indicates the type of authentication required, such as Basic realm=”Example”.
- The client encodes the username and password in the format username:password and converts it to a base64 string, such as b3dhaXMuYWxhbUBjbG91ZHdheXMuY29tOmVKNWtuU24zNVc=.
- The client sends the same request again, but this time with an Authorization header that contains the encoded credentials, such as Authorization: Basic b3dhaXMuYWxhbUBjbG91ZHdheXMuY29tOmVKNWtuU24zNVc=.
- The server decodes the credentials and checks if they are valid. If they are, the server grants access to the requested resource and sends a 200 OK status code. If they are not, the server denies access and sends another 401 Unauthorized Error.
Basic authentication should only be used over HTTPS connections or in situations where there is a high level of trust between the client and the server. The client must clear the cache or close the browser to end the session, as there is no logout or password change mechanism.
Authentication Methods for WordPress Rest API
The WordPress REST API provides several authentication options designed for a specific use case. These options include Basic Authentication, OAuth Authentication, and Cookie Authentication.
- Basic Authentication: A way to send a username and password with a request.
- OAuth Authentication: A way to let users give websites or apps access to their information on other websites without giving them their passwords.
- Cookie Authentication: A way to use cookies to check if a user is allowed to make a request and keep track of their session.
Cookie Authentication is the native WordPress authentication method for verifying users and their activities. However, you must install the respective plugins available from the WP API Team on GitHub to use OAuth and Basic Authentication with WordPress REST API.
Understanding WordPress REST API Commands
Before you install the WordPress Rest API plugin, let’s look at some of the common REST API commands you can use to interact with your WordPress site. These are mentioned below:
- GET: Use this command to retrieve a resource, such as a post or data, from the server.
- POST: Use this command to add a new resource to the server.
- PUT: Use this command to update or edit an existing resource on the server.
- DELETE: Use this command to remove a resource from the server.
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.
Harness the WordPress REST API & Optimize with Our Managed WordPress Hosting
With Cloudways, you can transform your development experience and build powerful applications with ease.
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:
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.
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:
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 http://wordpressmu-19393-42425-140587.cloudwaysapps.com/wp-json/wp/v2/posts/50
Where wordpressmu-19393-42425-140587.cloudwaysapps.com 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.
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:
jQuery.ajax({ url: 'http://wordpressmu-19393-42425-140587.cloudwaysapps.com/wp-json/wp/v2/posts/50', 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.
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 = 'http://wordpressmu-19393-42425-140587.cloudwaysapps.com/wordpress-api/wp-json/wp/v2/posts/50'; $wp_delete_post_response = wp_remote_request( $wp_request_url, array( '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
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 ); }, data:{ '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. You can easily use it with our managed WordPress hosting.
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.
Frequently Asked Questions
Q. How can I determine if the REST API is enabled in WordPress?
The REST API feature is included by default in WordPress versions 4.7 and later, so no additional configuration is necessary to use it.
Q. What ways can you authenticate with the WordPress API without a plugin?
There are currently four methods for authenticating with the WordPress API without using a plugin:
- Cookies
- Basic Auth
- OAuth
- JSON Web Tokens
To implement one of these methods, you can add the relevant code to your theme’s functions.php file. For example, if you want to use Basic Auth, you can add the Basic Auth code to your functions.php file, and it will be ready to use.
Owais Khan
Owais works as a Marketing Manager at Cloudways (managed hosting platform) where he focuses on growth, demand generation, and strategic partnerships. With more than a decade of experience in digital marketing and B2B, Owais prefers to build systems that help teams achieve their full potential.