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.

CloudwaysCDN — a powerful solution that offers superior performance and satisfied global audience for your business. Read More

How to Setup and Use WordPress REST API: Basic Authentication

Updated on  5th September

8 Min Read
setup basic authentication
Reading Time: 8 minutes

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 access to a particular system.

It is important to understand that authentication is different from authorization. When a person is authenticated on a particular server, they are granted a general level access to the system. In contrast, when a person is authorized, they are able to access and utilize part or complete resources of the system. In other words, authentication confirms the identity while authorization identifies and grants accesses 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.

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

At the moment, the native WordPress authentication manner for users and their activities is verification by cookies.

To use OAuth authentication and Basic Authentication with WordPress REST API, you need to install the particular plugins available on the GitHub WordPress REST API group. I hope that these two methods will receive native support in the next 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 headers of the request.

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 base64 encoded string. This string is sent in the Authorization header field as the following:

Authorization: Basic b3dhaXMuYWxhbUBjbG91ZHdheXMuY29tOmVKNWtuU24zNVc=

Since base64 strings could be decoded without much effort, this authentication method is not very secure. thus, this 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, simply clone it in the WordPress Plugin directory and activate it through the WordPress admin.

Send Authenticated Requests Using Postman

In order 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.

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

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 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.

If all goes well, the server will return a 200 OK status, indicating 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 could 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 the jQuery.ajax() method:

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

In the above request, I have set 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:

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:

Here, I have used  wp_remote_request() that accepts two arguments; $url (the URL of the request) and $args (the array that contain 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. At the time of successful login to the WordPress dashboard, the correct cookies are set up. Thus, the developers only have to log in for authentication.

However, the REST API incorporates a method called 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 a part of Javascript API, this is taken care of naturally for you. This is the prescribed approach to utilize 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 passed to the API through the _wpnonce data parameter (either POST data or in the query for GET requests), or by means of 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. As such, 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 suitable authorization for the activity being performed.

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

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

Conclusion

WordPress REST API is perhaps the most popular and extensively used REST API in the world. 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

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 owais.alam@cloudways.com

Make Your WordPress Website 100% Faster.

Host it now on Cloudways WordPress Hosting Platform.

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

THERE’S MORE TO READ.