How to resolve error in Google Storage Client in Symfony?

1.3k Views Asked by At

I am developing a project in Symforny 5 and I want to use Google Cloud Storage, install thephpleague / flysystem-bundle with superbalist / flysystem-google-storage support, as indicated in the documentation, generate the credentials.json in Google Console and the bucket, but I get the following error:

{
 "error": {
 "code": 401,
 "message": "Invalid Credentials",
 "errors": [
 {
  "message": "Invalid Credentials",
  "domain": "global",
  "reason": "authError",
  "locationType": "header",
  "location": "Authorization"
 }
 ]
}
}
\vendor\google\cloud-core\src\RequestWrapper.php (line 362)

Configurations:

flysystem:
storages:
    default.storage:
        adapter: 'local'
        options:
            directory: '%kernel.project_dir%/var/storage/default'

    gcs.storage:
        adapter: 'gcloud'
        options:
            client: 'gcloud_client_service' # The service ID of the Google\Cloud\Storage\StorageClient instance
            bucket: 'test-storage'
            #prefix: 'optional/path/prefix'
            api_url: 'https://storage.googleapis.com'

In service.yml

gcloud_client_service:
    class: Google\Cloud\Storage\StorageClient
    arguments:
        - projectId: 'storage-project'
        - keyFilePath: '../credentials.json'
2

There are 2 best solutions below

0
On

A bit late, but maybe it helps someone else. Today I had the same issue on Symfony 5.1, solved it by setting services.yaml this way:

services:    
      gcloud_client_service:
        class: Google\Cloud\Storage\StorageClient
        arguments:
          $config:
            keyFilePath: '%kernel.project_dir%/config/my_testing_config.json'
            projectId: 'my-testing-project'
0
On

The error you are getting because the credentials are not set correctly. If you want to use the JSON file, a way to solve this issue is setup the credentials inside your code using something like this:

putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');

On the other hand, At this this other documentation you can find another way on how to set the configuration of the connection to GCS. Also remember to add the Service Account that you ant to use, going to IAM and adding the "Storage Bucket Admin" role to that SA.

Both of these options should work for you.