PHP run local webserver, to fix Google authorization issue caused by the removal of OOB

one text

Google removed urn:ietf:wg:oauth:2.0:oob flow for installed / desktop / native applications. Making Google OAuth interactions safer by using more secure OAuth flows

This flow allowed for the redirect uri to return the authorization code back to an application that did not have a web server running.

The python samples for google-api-python-client compensate for this by spawning a local server.

flow = InstalledAppFlow.from_client_secrets_file(
            'C:\YouTube\dev\credentials.json', SCOPES)
creds = flow.run_local_server(port=0)

This works as would be expected the authorization code is returned properly to the application.

My issue is with PHP, and the Google-api-php-client library

The current samples I have found created by google look as follows

// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));

The user is prompted to copy the authorization code from the web browser themselves and paste it into the console window. In the past this was fine because urn:ietf:wg:oauth:2.0:oob would put the code in the web browser page. Now that is not happening. with the removal of oob we must use '"http://127.0.0.1"' when the authorization completes. a 404 error is displayed to the user in the browser window

enter image description here

However the url bar of the browser window displays the code

https://127.0.0.1/?state=xxxxxxx&code=xxxxxxxxxxxxxx&scope=googleapis.com/auth/youtube.readonly googleapis.com/auth/youtube.force-ssl googleapis.com/auth/yt-analytics.readonly

A user must then copy the code from the URL browser window. This is confusing for non-tenchincal users who see the 404 error and assume that something has gone wrong.

The issue is that the sample code does not spawn a web server as Python does in order to display the redirect uri properly.

My question: Is there a way to spawn a local server like python does with php? or is there an alternative to get this working again properly with php?

Full sample code

For anyone willing to test. Here is a full example.

  1. create installed credentials on google cloud console
  2. enable the google drive api.

Lots of code:

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

use Google\Client;
use Google\Service\Drive;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google Drive API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/drive.readonly');
    $client->setAuthConfig('C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json');
    $client->setAccessType('offline');
    $client->setRedirectUri("http://127.0.0.1");
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {

            $accessToken = json_decode(file_get_contents($tokenPath), true);
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->setAccessToken($accessToken);
    }

    // If there is no previous token, or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
try {
    $client = getClient();
}
catch(Exception $e) {

    unlink("token.json");
    $client = getClient();
    }

$service = new Drive($client);

// Print the next 10 events on the user's calendar.
try{


    $optParams = array(
        'pageSize' => 10,
        'fields' => 'files(id,name,mimeType)',
        'q' => 'mimeType = "application/vnd.google-apps.folder" and "root" in parents',
        'orderBy' => 'name'
    );
    $results = $service->files->listFiles($optParams);
    $files = $results->getFiles();

    if (empty($files)) {
        print "No files found.\n";
    } else {
        print "Files:\n";
        foreach ($files as $file) {
            $id = $file->id;

            printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
        }
    }
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}

Source