[API] How to Set up and Use OAuth Authentication Using WP REST API (ok0
https://www.cloudways.com/blog/setup-and-use-oauth-authentication-using-wp-rest-api/
Last updated
https://www.cloudways.com/blog/setup-and-use-oauth-authentication-using-wp-rest-api/
Last updated
When it comes to WordPress REST API, OAuth is the most common authentication handling provider.
When OAuth authentication is in place, users first login through the WordPress login form that is in use on the website. however, this login also authorizes the clients to handle requests on their behalf and all subsequent requests are validated through OAuth tokens. Those tokens are also used to manage all API access requests. This access could be revoked at any point.
Perhaps, the most important use of the OAuth authentication process is the safe process of handling REST API requests without exposing the credentials of the users. This is particularly important in the case of production servers where credentials are often exchanged. In such scenarios, OAuth authentication is used to provide a safe procedure for handling frequent login credentials request.Table of Contents
In order to understand the significance of OAuth authentication, it is important to understand the traditional and OAuth authentication model.
In the traditional authentication model, there are two key entities; Client and Resource/Service Provider. The client could be a web app, service or a user, while the Resource/Service Provider has the desired resources or services in an access-restricted environment.
When the Client requires a particular resource, it authenticates itself with the Resource Provider by providing appropriate credentials. While this is a simple process, there is also a huge risk of a security breach.
In contrast, OAuth authentication model is slightly more complex with three entities; Client that acts on behalf of the user, User who requires access to a resource, and the Server that maintains the resource.
Since there are three entities, the process is known as three-legged authentication. However, in cases where the Client and the User are the same entities, the authentication process becomes two-legged authentication.
The Client requests the User authorization to access the Server.
If the User grants the request, the Client receives the right to proceed further.
The Client presents its identity and the mandate from the Client to the Authorization Server (API) and requests a token.
In the event of successful validation of the identity and mandate, the Authorization Server (API) issues an access token to the Client. At this point, the authentication is complete.
Next, the Client approaches the Server to request a particular resource. At this point, the Client also sends the access token to the
If the access token is validated, the Server grants access to the resource requested.
The Client originates the signed request for a Request Token. This request is also known as Temporary Credentials. The request is sent to the relevant endpoint URI. This request comprises of several important parameters:
oauth_consumer_key: This key identifies the application originating the request.
oauth_timestamp: Servers use this timestamp for optimization of nonces storage.
oauth_nonce: This is the unique application generated token for every individual request.
oauth_signature: This important part of the API request is the hash of all components of the request and some OAuth values.
oauth_signature_method : The OAuth plugin offers a single signature method: HMAC-SHA1.
oath_callback : The URL where the user is redirected after authorization. The request is verified and a Request Token with the following parameters is issued.
oauth_token: This is the application token that is stripped from the response of the Authorization Server. This token is then sent to the API server.
oauth_token_secret: This is similar to the user password. The request is then authorized by the Client. For this, a request URI is created and oauth_token is added to the server authorization endpoint URI. The User authorizes sending this request by providing appropriate credentials.
In the event oauth_callback URI is available in the first step, the server redirects to the URI with the following parameters added to the query string:
oauth_token: already have the token.
oauth_verifier: verifies the identity of the resource owner to the client.
If the oauth_callback URI was not provided in the first step, then the server sends the value of oauth_verifier so that the resource owner could inform the client manually.
After receiving oauth_verfier, the client requests the server for token credentials. This takes the form of a request to the Token Request endpoint URI. This request contains the following parameters:
oauth_token
oauth_verfier
oauth_consumer_key
oauth_signature
oauth_signature_method
oauth_nonce
oauth_version
In the context of WordPress,OAuth authentication is implemented by installing the OAuth authentication API for WordPress. This is based on OAuth 1.0a specifications and actually extends these specifications by an additional parameter wp_scope. This parameter is sent to Temporary Credential Request endpoint.
The plugin is available on Github from the WP REST API team. At the moment, version 4.4 and later are supported.
I will start the process of cloning the plugin by moving to /wp-content/plugins/ directory:
git clone https://github.com/WP-API/OAuth1.git
After the download finishes, activate the plugin through WordPress CLI:
wp plugin activate OAuth1
If you do not wish to use WordPress CLI, you could go to the WordPress Admin >> Plugins and activate the plugin from the menu. 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.
Before I initiate the OAuth handshake, I will first check whether 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.
GET http://Server-Dev/wp-json/
This will return a JSON response as follows:
My 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
If the OAuth API is not enabled for a site, the server response would contain an empty authorization property value.
The first step is to make sure that the OAuth1.0 plugin is installed and activated correctly.
Next, I can create and manage applications by going to the WordPress Admin >> Users >> Applications.
On this Registered Applications page, I will register a new application by clicking the Add New button and then filling in the following three fields:
Client Name: The name of the Client that appears on the Authorized Applications section, and during the authorization process.
Description: The optional description of the Client.
Callback URL: The callback URL is used when generating temporary credentials.
Once created by clicking the Save Client button, the Client Key and Client Secret parameters will appear at the bottom of the page for this particular client.
I will now clone the repository on the client by running the following command:
git clone https://github.com/WP-API/client-cli
Now navigate into the cloned directory and install package dependencies using Composer:
cd client-cli
composer install
If all goes well, the command line should show something similar to the following:
To start the OAuth authorization process, I will first obtain the following parameters from the server:
oauth_consumer_key
oauth_consumer_secret
This will be generated through the terminal and running the following WordPress CLI command:
wp oauth1 add
The Key and Secret are the oauth_consumer_key and oauth_consumer_secret respectively.
Now I need to link the client to the WordPress site. On the client, navigate to the client-cli directory (cloned earlier) and run the following command:
wp --require=client.php api oauth1 connect http://Server-Dev/ --key=<your key here> --secret=<your secret here>
Replace the URL, the key and the secret in the above command. The output should be like the following:
wp --require=client.php api oauth1 connect http://your-server/wordpress-api/ --key=<your key> --secret=<your secret code>
Open in your browser: http://your-server/wordpress-api/oauth1/authorize?oauth_token=<your-token>
Enter the verification code:
Navigate to the URL given by the server and authenticate by clicking the Authorize button:
You will be presented with the verification token (or the oauth_verifier) on the next screen:
Copy the verifier and paste it into the terminal. You will be given a Key and a Secret, which are basically the oauth_token and oauth_token_secret respectively:
Because the OAuth 1.0a server plugin follows the standard three-legged flow, generating OAuth credentials involves the following steps:
Acquisition of temporary credentials
User authorizations
Token exchange
I will send a POST request to /oauth1/request endpoint to get temp credentials. Note that this endpoint should be auto-discoverable as a server might replace the route on its own.
The POST request should include and oauth_consumer_secret parameters as acquired when registering a consumer for the application. The request might also include the oauth_callback parameter and this callback URL should match the scheme, host, port, and path of the callback URL which was provided when registering the application.
In addition to the oauth_consumer_key and oauth_consumer_secret parameters, the request should also include the oauth_signature and oauth_signature_method parameters.
When using Postman, the oauth_signature is generated automatically. I only need to mention the oauth_signature_method parameter. At the moment, only the HMAC-SHA1 signature method is supported by the OAuth server plugin.
I will now configure Postman to send a POST request to the temporary token credentials endpoint. Next, in the Authorization tab, select the OAuth 1.0 option from the dropdown. Fill in the Consumer Key and Consumer Secret fields with the values provided by the consumer. Finally, check that the Signature Method option is set to HMAC-SHA1.
For the user authorization step, I will open the resource owner authorization endpoint in the browser and pass the oauth_token and oauth_token_secret as obtained in the previous step as query parameters:
http://server-dev/oauth1/authorize?oauth_token=<token_here>&oauth_token_secret=<secret_here>
Authorize the application by clicking the Authorize button. The next screen will present a verification token. This token will now act as an oauth_verifier token in the next step.
Once the user has authorized the client, the application will appear under the Authorized Applications section on the Users > Your Profile page.
By using the OAuth 1.0 option again in the Authorization tab, fill in the fields for Consumer Key and Consumer Secret with values as provided by the consumer. In the fields for Token and Token Secret, insert the value oauth_token and oauth_token_secret parameters (temporary credentials).
As I can also pass parameters in the URL as query parameters, append the oauth_verifier parameter to the URL as follows:
http://server-dev/oauth1/access?oauth_verifier=<oauth_verifier_value>
With all the parameters in place, send the request by clicking the Send button. If all goes well, the server will return a 200 – OK status code along with the response body containing oauth_token and oauth_token_secret parameters.
oauth_token=<oauth_token_value>&oauth_token_secret=<oauth_secret_value>
At this point, the temporary tokens acquired earlier are discarded and can no longer be used.
The new oauth_token and oauth_token_secret parameters are the OAuth credentials that you can use in the client for generating authenticated requests.
Now that I have the token credentials, I will send a test request to the server using the Postman. The request will require the following parameters:
You will need to have the following before you get started:
oauth_consumer_key
oauth_consumer_secret
oauth_token
oauth_token_secret
Select OAuth 1.0 from the drop-down under the Authorization tab in Postman.
Once you have filled all the fields, click the Update Request button. Check Add params to header option to send the parameters in the header of the request instead of appending to the query string.
If the request is successful, the server will send a 200 – OK status code.
In this tutorial, I discussed how to setup OAuth authentication API for WordPress on a server, and how to use the HTTP client for obtaining token credentials. If you discover an issue in the code or would like to add to the discussion, please leave a comment below.
Start Growing with Cloudways Today!
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
November 30, 2016 8 Min Read
We never compromise on performance, security, and support.TEST NOW