-1

I am using v1 API to read text from image in a Laravel web app.

But I have to generate tokens after they expire.

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:method

Is there any other better way for authentication to Google Cloud API in Laravel ?

JM Gelilio
  • 3,482
  • 1
  • 11
  • 23
Pankaj S Y
  • 11
  • 1
  • 4
  • If you are running your Laravel application in Google Cloud, then the preferred method is to use ADC (which will select the default service account). You can use either the Google Cloud SDK for PHP or one of the Laravel packages such as **superbalist/laravel-google-cloud-storage**. That Laravel package also integrates into the Laravel filesystem. – John Hanley Jul 19 '21 at 19:18
  • The Laravel application is in Microsoft Azure. – Pankaj S Y Jul 20 '21 at 03:35
  • 1
    Which version of Laravel and which service on Azure. Details often make a big difference in receiving a good/correct answer. – John Hanley Jul 23 '21 at 20:50
  • Laravel version 8 and App Service on Azure. – Pankaj S Y Aug 01 '21 at 13:38

1 Answers1

2

The best way and recommended to handle and manage auth credentials is to use the official tools offered by Google. Use Auth Library for PHP , then integrate it with the HTTP client that you use.

The scope for Cloud API is: https://www.googleapis.com/auth/cloud-platform

For Example:


use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// specify the path to your application credentials
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');

// define the scopes for your API call
$scopes = ['https://www.googleapis.com/auth/cloud-platform'];

// create middleware
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://LOCATION-documentai.googleapis.com',
'auth' => 'google_auth' // authorize all requests
]);

// make the request
$response = $client->get('v1/projects/PROJECT_ID/locations/LOCATION/processors/PROCESSOR_ID:method');
JM Gelilio
  • 3,482
  • 1
  • 11
  • 23
  • 1
    This answer works with one change for Laravel 8. The Google auth library does not support Guzzle 7. Change **composer.json** to `"guzzlehttp/guzzle": "^6.5|^7.0.1",` – John Hanley Jul 23 '21 at 20:49