WP Manifestindependent plugin directory
manifest / developer / wp-plugin__oauth-demo

_ANDYP - Demo of Google OAUTH

Demo of how to get google OAUTH working in wordpress.

by Andy Pearson · github.com/ioroot/wp-plugin__oauth-demo · website

2stars
0forks

Install

No release zip yet. The repository archive installs, but the folder name will carry the branch suffix and updates will not flow:

wp plugin install https://github.com/ioroot/wp-plugin__oauth-demo/archive/refs/heads/master.zip

Readme

ACF OAuth How-To.

How-to Tutorial and Demo of getting google OAUTH working with wordpress through ACF.

Wordpress & Google OAuth

This plugin will create a simple shortcode for a button that will open an OAUTH window to request permissions to use YouTube of the user. It utilises the Google API client library and services composer packages.

This demo is about a simple as I could make it. However, it's still a little convoluted in my opinion. I'm sure there are better ways of doing it.

I've taken lots of concepts and ideas from https://github.com/ohfuchs/acf-oauth so if you want a full ACF Oauth package, then this is a great one to use.

However, in my use-case, I wanted to use the google api client library https://github.com/googleapis/google-api-php-client and it's services. Therefore I had to work out the steps of going about doing all this myself.

1. Table of Contents

2. Installation

You will need to do the following steps:

  1. Clone the repo into your wp-plugins directory.
  2. Activate the plugin.
  3. Create a new google API project with OAuth 2.0 credentials in the google API Console. https://console.developers.google.com/
  4. Add the YouTube Data API v3 API into the project.
  5. You may have to set up consent pages and usage agreements.
  6. You must add https://MYDOMAIN.com/wp-admin/admin-ajax.php as an Authorized redirect URI.
  7. Download the JSON credentials into the root of the plugin folder and call the file client_secret.json
  8. Run a composer install in the plugin folder to install all dependencies (google-api-php-client and google-api-php-client-services).
  9. Run a composer dumpautoload to autoload all of the classes.
  10. Use the shortcode [andyp_oauth] on a page to render the OAUTH button.

3. How it works

The OAuth workflow seems to be quite a tricky and complex workflow to follow, but once you break it down into it's component parts, it's much more manageable to understand. Here are the parts:

3.1. Step 1 - Creating an Application

Telling google you have an application and you want to give it permissions to use a specific API

You can use the Google API Console (https://console.developers.google.com/) service to create a new project that tells google you are creating a new web application. Once you go to the website you'll want to do the following things:

  1. New Project. A project is all the settings for this application you are creating. You can create multiple projects for different purposes. Each project has quotas on how much it can use each API. Give the project a name and create it.

  2. Consent Screen. Here you can select the different parts of the project that the user will see when authorising your application.

  3. Library. Under the library sidemenu option you can select the specific APIs you want to use. In this demo I'm using theYouTube Data API v3 Select that and enable it.

  4. Credentials. Now you have to setup a way to use this new project. There are three methods available, each with a different use-case. API Keys, OAuth 2.0 Client IDs, and Service Accounts. Click the button at the top of the page + CREATE CREDENTIALS and select "OAuth client ID".

  5. Application Type. This is a "web application". This dictates the way the OAuth process works.

  6. Name. Give your OAuth client ID an appropriate name.

  7. Authoized redirect URIs. These MUST be exactly right. slashes on the end make a difference, as well as the protocol of http or https.

  8. Download JSON. Once all of the details are filled in, download the JSON file with all of the credentials to the root of the demo plugin folder and call the file client_secret.json. It must be called this because a constant called DEMO_APPLICATION_CREDENTIALS looks for this file.

Now you have setup a way to communicate with google. They now know you have an application that needs access to different people's YouTube accounts depending on who authorises it.

They also know a user will be using the OAuth 2.0 workflow to tell them to allow your application to have permission to use their YouTube account.

Lastly, they know that once the user has completed granting access to their account for your application, google will redirect them back to https://yourdomain.com/wp-admin/admin-ajax.php

3.2. Step 2 - Composer

Composer is a package manager that automatically installs any php packages you want. In our case, we want to install the Google API client and the YouTube service that comes with it. The installation method is described on their github page here: https://github.com/googleapis/google-api-php-client

My composer.json file tells composer what to install. So, by running composer install you'll install everything you need.

3.3. Step 3 - Shortcodes

/src/shortcode/button.php

This uses the wordpress add_shortcode function to declare the word andyp_oauth as the name of the shortcode and a function to run.

This function then does two things:

  1. It renders a <button> with a specific ID that will be picked up by our javascript later.

    id="andyp__youtube-oauth--button"

  2. It runs our demo_youtube class and returns any result in JSON. On initial installation, this will be nothing because we haven't authenticated yet.

Add the shortcode [andyp_oauth] onto any page and it'll render the button and any result as a JSON object.

3.4. Step 4 - Enqueue Javascript

/src/js/enqueue_js.php

This is where we start getting into the nitty-gritty. Before we start, you'll notice there are comments all over and some code commented out, this is because this demo app is meant for the frontend. However, the commented out bits allow you to use the code in the backend too. For instance, the add_action at the top of the page has a commented out second declaration for admin_enqueue_scripts for backend usage too.

This file will run the wp_enqueue_scripts wordpress action on the function we define in this file. This then does the following things:

  1. Adds jQuery and our custom demo_oauth.js script.

  2. Create a new Google_Client object from the google-api-client-php package.

    /*     
    * Generate AUTH URL with Google Client Library.
    */
    $client = new Google_Client();
    $client->setAuthConfig(DEMO_APPLICATION_CREDENTIALS);
    $client->addScope( Google_Service_YouTube::YOUTUBE_FORCE_SSL );
    $client->setPrompt('consent');
    $client->setAccessType('offline');

    This will build up a new Google Client object.

    set the Authentication config (using our client_secrets.json file - assigned to that constant).

    Add a YouTube Scopes . Think of a scope as a specific permission level - YOUTUBE_FORCE_SSL is a full access permission level.

    Finally, Set a consent screen to show and that we want offline access.

  3. The next part is to utilise the state parameter that we can send to the google OAuth server, but it's essentially not used by them, it's for us on the return back once the user has been authentiated.

    What we're going to do is use wordpress's AJAX functionality to read any returned values and do something with them. The way we have to set this functionality up is by redirecting back to the admin-ajax.php file (remember we specified that in the Google console as the return URI).

    However, this file expects at least one parameter called 'action' to indicate which function you want it to run.

    The head-scratcher problem is that the google API does not have an 'action' parameter and won't allow any extra ones to be added. This is where the state parameter comes in. We're going to send a json_encoded array of 'action' = 'demo_oauth_callback' within the state parameter and setup (later - see below) a catcher to json_decode the state parameter and append it's contents (this key-value pair) as an extra parameter BEFORE it gets sent to the admin-ajax.php file. Cool, huh?

    Alright, well, to setup this state parameter, we do this:

    /**
    * The "action" parameter tells the admin-ajax.php system 
    * which Action to run.
    * In this case, the action is "demo_oauth" which is 
    * definedas an AJAX endpoint in the 
    * /actions/oauth_callback.php file.
    */
    $demo_state_args = array(
        'action' => 'demo_oauth_callback'
    );
    
    $state = base64_encode( json_encode( $demo_state_args ) );
    
    $client->setState($state);
  4. The google client library allows us to generate an authentication URL based off all the settings we specified above. To do this is a one-liner:

    $auth_url = $client->createAuthUrl();

    This will return with a long URL that we can visit to open up the start of the OAuth process. However, we want to send it to our Javascript to open up a new tab window instead.

  5. The last part is the take the generated Authentication URL and make it available to our Javascript on the front-end. To do this, we can utilise the wordpress wp_localize_script function to send any values to the frontend. We want two values:

    • The admin-ajax.php file url.
    • The authentication url we just generated.

    The wp_localize_script needs to know which javascript file to tie the values to and the name of the data object to nest these values under.

    /**
    * Make these values accessible in the Javascript file.
    * 
    * In JavaScript, these object properties are accessed as 
    * ajax_object.ajax_url
    * ajax_object.auth_url
    */
    wp_localize_script( 'demo-oauth-script', 'ajax_object', 
        [
        'ajax_url' => admin_url( 'admin-ajax.php' ), 
            'auth_url' => $auth_url
        ] 
    );

    This then will link to the demo-oauth-script which we enqueued at the top of the function. And the object with all the data is called ajax_object.

Ok, so we've now loaded our javascript into our footer of the page, our authentication URL has been generated and we've made that available to the javascript.

3.5. Step 5 - Javascript

/src/js/demo_oauth.js

When you open this file up you can see it's pretty damn basic.

(function($){
/**
* The ajax_object.auth_url object is passed in from the 
* wp_localize_script function in enqueue_js.php file. 
*/
$('#andyp__youtube-oauth--button').on( 'click', function(){
        var win = window.open( 
            ajax_object.auth_url, 
            "_blank", 
            "width=600,height=600" 
    );
});

})(jQuery);

All this does is the following:

  1. Make the jQuery available as $
  2. Search for our button ID '#andyp__youtube-oauth--button'
  3. Attach a click event onto it which will run a function.
  4. The function will create a new blank window that point to the authentication URL we created in the enqueuing process above.
  5. Success!

3.6. Step 6 - OAuth

At this point, the user will click the button and open the new window with the authentication URL as the target. They will be presented with the OAuth steps from Google to select a user / account from YouTube and to allow access to the project.

Note - You WILL get a warning saying "This App isn't Verified". You'll need to click on the 'Advanced' link and then the "Go to yourdomain.com (unsafe)" to proceed.

This will disappear once your app has gone through the google verification process. However, for this demo purposes, there's no need.

Read the full README on GitHub →