Erik Peña
Uncategorized

Enabling OAuth 2.0 for WordPress

This article covers setting up an OAuth server within WordPress that complies with the OAuth 2.0 standard.  This is done to allow authorized API access against your installation of WordPress.

For the sake of this document, I’ll be covering the Authorization Code grant type which is the most readily available mechanism for setting up an OAuth server (most products offer Authorization Code grant type free).

Installing the OAuth Server

First things first, you will need to acquire the OAuth server WordPress plugin.  The link to this is https://wordpress.org/plugins/oauth2-provider/.  The developer for this plugin offers this plugin with a limited set of functionality for free and offers a pay-for-pro to obtain additional feature sets (More info on this on their website).  I have found that the free version is sufficient for my purposes given that my use cases are to authenticated from a web app.

After you have installed and enabled the plugin, you can go to the “OAuth Server” > “Clients” menu item in your WordPress installation.  Here, you will add a new Client Name and Redirection Url.  The Redirection Url is pre-determined Url that WordPress will redirect the user to after the user has successfully authorized access to the application.  Be sure to use a valid Redirection Url as the OAuth server will force the user to be redirected to the value that you define here.  Be sure to also check the “Authorization Code” checkbox to enable this grant type.

If your plans are to use this OAuth server to perform API requests against your WordPress installation, you’ll likely want to set the “Client Credential Assigned User” field to a user with the appropriate level of permissions.  Otherwise, if all you are doing is using the OAuth server to authenticate user access, you can leave this control alone.

After saving the Client configuration, you will be presented the OAuth configuration for the application which includes the Client ID and Client Secret.

Tip — If you’re developing your application and testing it against your OAuth server, you can modify your system’s hosts file to have the domain you specify to resolve to your localhost.  Make sure to reset your hosts file when you are done.

Recommendation — In a real-world case, you will never have your Client Secret value implemented on any client code.  Brokering OAuth calls are generally done through a web service layer that abstracts logic and that securely holds any secrets.

Verifying OAuth

To verify the OAuth server, I am choosing to demonstrate how the Authorization Code grant type flow works using POSTman as opposed to any specific client library implementation.  The reason for this is that I want to educate the reader with a deeper understanding of the authentication flow so that they are armed with with this knowledge which helps when troubleshooting a client integration.

The Authorization Code grant type flow involves two (2) steps to be considered successful (not more or less).  Here is a primer of the purpose each of these steps–

authorization – The authorization step is a visual process that requires the user to manually sign into your WordPress installation using their WordPress user permissions.  The result of this is a code value that gets used in the next step.

token – Using the Client ID, Client Secret and the code values, a request is made to generate and acquire an access token that is used for the API calls.

Bonus — If you want to verify an access token, you can utilize the following step.  This is recommended if you are caching access tokens on the client and need to validate them.

me – This step resolves the user’s metadata from your WordPress installation using the access token that was issued to them.  You would use this if you needed to retrieve additional user information such as the user’s username, email, status, etc.

To figure out what the OAuth Urls are for your WordPress installation, you can make a request against your root with a “/wp-json” appended to the url.  For example, if the root to your WordPress server was “https://www.somecoolblog.com”, you can expect this url to be “https://www.somecoolblog.com/wp-json”.

Making a request to this Url will return a huge Json response.  In this response, you can do a search for “oauth2” to find the urls you’ll need.  Below is an example of what to expect (truncated for brevity)–

{
    ...
    "authentication":{
        "oauth2":{
            "authorize":"https:\/\/www.somecoolblog.com\/oauth\/authorize",
            "token":"https:\/\/www.somecoolblog.com\/oauth\/token",
            "me":"https:\/\/www.somecoolblog.com\/oauth\/me",
            "version":"2.0",
            "software":"WP OAuth Server"
        }
    },
    ...
}

With the Client ID, Client Secret and the Urls above, we can now make the calls to verify the OAuth configuration.

Authorization Call

The authorize call is part programmatic/part manual in that your application will need to generate a Url that your user will need to be automatically redirected to.

To generate the authorize Url, take the url defined by WordPress and apply a “client_id” query parameter and set the value of this query parameter to the Client ID that you generated when creating the Client configuration in WordPress.  Also, add a “response_type” query parameter with a static value of “code”.  This generated authorize Url should look similar to the following–

https://www.somecoolblog.com/oauth/authorize?client_id=XP9zkkOvWMiG1EcWFVBlLWnUxyfiUWgSLqr5KgBH&response_type=code

In your browser of choice, request this authorize Url.  This simulates what the application will do by redirecting the user to the authorize Url programmatically. Assuming that the user already has an active session in your WordPress installation, the user will already be authenticated and redirected back to your web application.  If the user does not have an active session, they will be presented with a Sign In page where they will use their WordPress user credentials to sign in.

After your WordPress installation has authenticated the user, the user will be redirected back to your web application.  The Redirection Url that was defined when creating the Client configuration is used.  You will notice that the Url that the user is redirected to also contains a query parameter with a key of “code”.  In my case, the code value that came back from this call was “rijlgt8pl4hu7nb9ozwolwnuvgyf70zy3ok1iqqc”.

Token Call

To make the token call in POSTman, define the “token” url in the Url field, set the method to “POST” and open the Body tab.  In the Body tab, select the “x-www-form-urlencoded” option.  Below is a summary of the Key and Value field configurations that you will need to define.  The grant_type form parameter should be statically set with “authorization_code”.  Please remember to update the values as appropriate to represent your Client configuration and Code.

Key Value
grant_type authorization_code
client_id XP9zkkOvWMiG1EcWFVBlLWnUxyfiUWgSLqr5KgBH
client_secret 2Tn3yA0dwCzhyWc6vsoqoFia6JgRZRy2LV5kv6y1
code  rijlgt8pl4hu7nb9ozwolwnuvgyf70zy3ok1iqqc

POSTman should look like similar to the following–

Click the “Send” button to initiate the call.  Upon response, you’ll get a body that contains the new access token that can be used in API calls against WordPress–

Note — In this response, you will also have other interesting parameters.  The “expires_in” represents the seconds until the “access_token” has expired (My example equals one hour) to which you will need to go through this process again.  If you have the pro version of the OAuth Server WordPress Plugin, you would be able to utilize the “refresh_token” to get another valid “access_token”.

That’s it!  You just manually walked through the Authorization Code grant type flow of OAuth 2.0.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.