Google removedurn: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 becauseurn: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
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?
For anyone willing to test. Here is a full example.
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();
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.