WP REST API: Setting Up and Using OAuth 1.0a Authentication

In the previous part of the series, we set up basic HTTP authentication on the server by installing the plugin available on GitHub by the WP REST API team. The basic authentication method allows us to send authenticated requests by sending login credentials in the request header. While being quick and handy, there’s also a chance that these credentials might fall in the wrong hands. Hence this method should only be used on secure networks for development and testing purposes only.

For using authentication on production servers, there needs to be a more secure way of sending authenticated requests without risking exposing the login credentials. Thanks to the OAuth authentication method, those requests can be sent without exposing the username and the password in an unsafe manner.

In the current part of the series, we will learn to set up and use the OAuth authentication method to be used with the WP REST API plugin. To be specific, we will:

  • take an overview of the OAuth authentication method and how it works
  • install the OAuth server plugin
  • install the client and its dependencies
  • fix a potential bug involving base URL
  • generate an OAuth access token to be used in our app

Let’s begin by introducing ourselves to the OAuth authentication method.

Introducing OAuth Authentication

What do you do when you need to log in to your WordPress admin? You simply go to the login page and enter your login credentials, right? That’s simple! But what if you are using a third-party service that requires access to your WordPress resources (posts, pages, media, or anything else)? Would you simply hand over your login credentials to that service, knowing that they might end up in wrong hands whenever the integrity of that service is compromised? The answer would probably be “No”.

In the traditional model of authentication, there are two roles:

  1. The client: can be a user, application, or service
  2. The resource provider: the server where the protected resources are located

If a client wants to access protected resources, he or she would get authenticated by providing appropriate credentials to the server and would be granted access.

The problem arises when a third-party service needs access to these protected resources on the server. This service can’t be (and should not be) given credentials by the user to access resources. Providing credentials to a third party means giving away complete control over the resource located at the server. 

That’s where the OAuth authentication methodology come to the rescue. It introduces a new role in the authentication process, and it’s the resource owner. Now there are three roles in the authentication process:

  1. The client: not the user itself but a third-party application or service acting on behalf of the user and accessing protected resources
  2. The server: the server where the protected resources are located
  3. The resource owner: the user itself

The above three roles together make what is termed as three-legged OAuth authentication. The number of legs define the roles involved in an authentication process. When the resource owner is also the client, the flow becomes known as two-legged authentication.

According to Webopedia:

OAuth is an open authorization standard used to provide secure client application access to server resources. The OAuth authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf.

OAuth enables server owners to authorize access to the server resources without sharing credentials. This means the user can grant access to private resources from one server to another server resource without sharing their identity.

Hence in OAuth authentication flow, the user doesn’t need to expose credentials but can authorize the client to act on its behalf, deciding what resources the client can access. In other words, while not giving login credentials, the user can also decide the scope of the access the client is being granted.

This enables not only websites but also desktop and mobile applications to gain limited access to a resource on a server.

In terms of WordPress, OAuth informs the resource provider (the WordPress installation) that the resource owner (the WordPress user) has granted permission to access to a third-party application to access their resources. These resources can be anything like posts, pages, taxonomy and media, etc. This permission can be for limited or complete access, as we will see later in this tutorial.

How the OAuth Authentication Flow Works

The OAuth authentication API for WordPress is built on top of OAuth 1.0a specifications, hence we will be taking a look at how OAuth 1.0a works.

OAuth works by using token credentials that are issued by the resource provider (the server), at the request of the resource owner after it has authenticated itself by using its credentials. These tokens—associated with the resource owner—are then used by the client (a third-party application or service) to gain access to protected resources.

The OAuth flow goes as follows:


  1. The client sends a signed request to the server for obtaining a Request Token, also known as Temporary Credentials. This request is sent to the Temporary Credentials endpoint URI, and it contains the following:

    • oauth_consumer_key: provided by the server
    • oauth_timestamp
    • oauth_nonce
    • oauth_signature
    • oauth_signature_method
    • oath_callback
    • oauth_version (optional)

  2. The server verifies the request and if it’s valid, grants a Request Token that contains:

    • oauth_token
    • oauth_token_secret
    • oauth_callback_confirmed
  3. The client then sends the resource owner (the user) to the server to authorize the request. This is done by constructing a request URI by adding the oauth_token obtained in the previous step to the Resource Owner Authorization endpoint URI.
  4. The resource owner (the user) authorizes at the server by providing credentials.

  5. If the oauth_callback URI was provided in the first step, the server redirects the client to that URI and appends the following as query string:

    • oauth_token: obtained in the second step
    • oauth_verifier: used to ensure that the resource owner who granted access is the same returned to the client
  6. If the oauth_callback URI was not provided in the first step, then the server displays the value of the oauth_verifier so that the resource owner could inform the client manually.

  7. After receiving the oauth_verfier, the client requests the server for token credentials by sending a request to the Token Request endpoint URI. This request contains the following:

    • oauth_token: obtained in the second step
    • oauth_verfier: obtained in the previous step
    • oauth_consumer_key: provided by the resource provider (the server), before starting the oauth handshake
    • oauth_signature
    • oauth_signature_method
    • oauth_nonce
    • oauth_version

  8. The server verifies the request and grants the following, known as Token Credentials:

    • oauth_token
    • oauth_token_secret
  9. The client then uses Token Credentials to access protected resources on the server.

The above information can either be transported by a query string appended to request URIs or by including it in the Authorization header, though the latter is recommended due to better security.

This is a lengthy process and should be taken into account when developing our own clients to interact with the API. The purpose of the client is to manage all this jargon and facilitate the user in the authentication process. Since we will be using a package provided by the WP REST API team, the above details will be abstracted away and we will be able to gain token credentials in a minimum number of steps.

In the above discussion, we came across three endpoint URIs, namely:

  1. Temporary Credential Request endpoint
  2. Resource Owner Authorization endpoint
  3. Token Credentials Request endpoint

These URIs are provided by the server in various ways. One of these ways is by exposing them in the server response when checking for the API. The OAuth authentication API for WordPress REST API uses the same method, as we will see in the next section.

Having looked at how OAuth works, our next step is to install and enable the OAuth authentication API for WordPress.

Installing the OAuth Authentication API for WordPress

The OAuth authentication API for WordPress enables the server to accept authenticated requests using OAuth implementation. It’s built on top of OAuth 1.0a specifications and extends them by an additional parameter—wp_scope—to be sent to the Temporary Credential Request endpoint. The wp_scope parameter defines the scope of the access being granted to the client. You can find more about it in the official documentation.

The plugin is available on Github from the WP REST API team.

Let’s clone the plugin by navigating to the /wp-content/plugins/ directory:

After download completes, activate the plugin using WP CLI:

Alternatively, you can also activate it by navigating your browser to your WordPress admin plugins section if you don’t wish to use WP CLI.

This is all that’s needed to enable the server to accept OAuth as an authorization method. The next thing we need to do is to send a request to the server to check if OAuth API is ready to be used.

Assessing the Availability of the OAuth API

Before we initiate the OAuth handshake, we should first check if the API is enabled on the server. This is done by sending a simple GET request to the /wp-json/ endpoint and then analyzing the response sent by the server.

Fire up your HTTP client and send a request to the /wp-json/ endpoint as follows:

This will return a JSON response as follows:

Server response

Our focus here is the oauth1 value in the authentication property value. This object has the following properties defined:

  • request: the Temporary Credential Request endpoint
  • authorize: the Resource Owner Authorization endpoint
  • access: the Token Request endpoint
  • version: the version of OAuth being used

The first three of them are absolute URLs that we came across when learning about the OAuth mechanism in a previous section.

The oauth1 object defined in the authentication property value shows that the OAuth API has been successfully enabled for our WordPress site and we can start using it.

If the OAuth API is not enabled for a site, the server response would contain an empty authorization property value as follows:

Server response

We are now ready to install the client package provided by the WP REST API team to interact remotely with a WordPress site and generate token credentials.

Installing the Client CLI Package

The Client-CLI package by the WP REST API team allows remote interaction with a WordPress site using WP-CLI and WP REST API. The source can be found on GitHub.

To use this package, you will need to have the following installed and activated on the server where your WordPress installation is located:

  1. WP CLI
  2. WP REST API plugin
  3. OAuth 1.0a server plugin

On the machine (or client), from which you wish to generate requests, the following must be installed:

  1. WP CLI
  2. Composer
  3. The Client CLI repository itself

You can find the instructions to install the above packages on their respective sites.

With that said, let’s clone the repository on the client by running the following command:

Now navigate into the cloned directory and install package dependencies using Composer:

If all goes well, the command line should show something similar to the following:

OAuth10a installed

Now that we have installed the package, we are ready to generate token credentials and interact remotely to WordPress REST API using OAuth.

Using Client CLI to Generate Token Credentials

To start the OAuth authorization process, we first obtain the following from the server:

  • oauth_consumer_key
  • oauth_consumer_secret

This can be generated by directing the terminal to your WordPress installation directory on the server and running the following WP CLI command:

This will generate an output like the following:

Generating consumer key

The Key and Secret obtained here are the oauth_consumer_key and oauth_consumer_secret respectively.

Now we need to link the client to our WordPress site. On the client, navigate to the client-cli directory you cloned in the previous section and run the following command:

Replace the URL and also the key and the secret you obtained in the previous step in the above command. The output should be like the following:

Navigate to the URL given by the server and authenticate yourself by clicking the Authorize button:

User authorization

You will be presented with the verification token (or the oauth_verifier) on the next screen:

Verification token

Copy the verifier and paste it into your terminal. You will be given a Key and a Secret, which are basically your oauth_token and oauth_token_secret respectively:

Token credentials

You can use these token credentials in your HTTP client or any other application that supports sending authenticated requests using the OAuth API.

Fixing a Potential Base URL Issue

The WordPress REST API and the OAuth authentication API for WordPress is still evolving, so they are prone to bugs and errors at this initial stage. One such issue arose when I first tried to generate token credentials using the WordPress OAuth API and the Client CLI package. And it’s quite possible that you encounter the same issue while following this tutorial. But don’t worry, as we have got you covered!

The issue arises when trying to link the client to the WordPress site using the oauth_consumer_key and oauth_consumer_secret. The server might respond with a 401 – Unauthorized or OAuth signature doesn’t match error.

This is because the current OAuth API plugin doesn’t take into account the subdirectory your WordPress is located in. Rather it assumes that WordPress is installed in the root directory, and this causes the OAuth signature on the server to be different than that sent by the request.

Luckily I found the solution in the pull requests of the official GitHub repository of the OAuth API plugin.

The solution involves modifying the lib/class-wp-json-authentication-oauth1.php file of the OAuth API plugin on line 524 to change the following code:

to:

After making the above changes, you should have no problems linking the client to the site.

Sending a Test Authenticated Request

Now that we have obtained our token credentials, we can send a test request to the server using Postman to see if they work (of course they will!).

We will send a DELETE request to the server to delete a post with an id of 50. This id can be different in your case.

You will need to have the following before you get started:

  • oauth_consumer_key: obtained in the first step
  • oauth_consumer_secret: obtained in the first step
  • oauth_token: obtained in the final step
  • oauth_token_secret: obtained in the final step

Select OAuth 1.0 from the drop-down under the Authorization tab in Postman, and fill the first four fields as mentioned above. Below is what it looks like:

Using OAuth1

Click the Update Request button after filling in the fields. Checking the Add params to header option sends the parameters in the header of the request instead of appending them in a query string.

Send the request and you should get a 200 – OK status code from the server, showing that the post has been deleted successfully.

Conclusion

In this lengthy tutorial we took an overview of the OAuth authentication method and how it works to provide safe delegated access to third-party applications and services. We also set up the OAuth authentication API for WordPress on the server and used it in conjunction with the Client CLI package provided by the WP REST API team to obtain token credentials.

In the next part of this series, we will be looking at retrieving content through the WP REST API. So stay tuned…

Leave a comment

Your email address will not be published.