phpgoogle-apigoogle-cloud-storagegoogle-oauthgoogle-cloud-speech

Google Cloud Storage is giving me Authorization code 401 Invalid Credentials when trying to connect


  1. I have completed the guides here
  2. Also i have completed this guides as well (as I want to use both Storage and Speech)

Now i have gcloud and it is working in the terminal i also tried executing this command from the shell:

curl -s -H "Content-Type: application/json" \
    -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
    https://speech.googleapis.com/v1/speech:recognize \
    -d @sync-request.json

And it is working as I am getting:

{
  "results": [
    {
      "alternatives": [
        {
          "transcript": "how old is the Brooklyn Bridge",
          "confidence": 0.9840146
        }
      ]
    }
  ]
}

But when i try to put some code. For example this one:

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

// Imports the Google Cloud Storage client library.
use Google\Cloud\Storage\StorageClient;

function auth_cloud_implicit($projectId)
{
    $config = [
        'projectId' => $projectId,
    ];

    # If you don't specify credentials when constructing the client, the
    # client library will look for credentials in the environment.
    $storage = new StorageClient($config);

    # Make an authenticated API request (listing storage buckets)
    foreach ($storage->buckets() as $bucket) {
        printf('Bucket: %s' . PHP_EOL, $bucket->name());
    }
}

# Your Google Cloud Platform project ID
$projectId = 'somenumbersandletters';

auth_cloud_implicit($projectId);

I am getting this error:

Google\Cloud\Core\Exception\ServiceException: { "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } } in /var/www/speech/vendor/google/cloud-core/RequestWrapper.php on line 263

So my question is what i am doing wrong and why this code is not working? I have do the same code on other computer and it is working fine, i do not get it why it is not working over this computer the same way? Any suggestions will be more then welcome!


Solution

  • UPDATE 2022

    $config = [
        'credentials' => [PATH-TO-JSON-FILE],
    ];
    
    $client = new BetaAnalyticsDataClient($config);
    

    UPDATE 2018

    use Google\Auth\Credentials\GCECredentials;
    
    $gceCredentials = new GCECredentials();
    $config = [
        'projectId' => $projectId,
        'credentialsFetcher' => $gceCredentials,
    ];
    

    What i have noticed is that when you want to instantiate a Google Service you just have to put the JSON file inside the array and it should work. For example if you want to instantiate Google Speech Client simply do this:

    $speech = new SpeechClient([
        'projectId' => $projectId,
        'keyFilePath' => 'path/to/file.json',
        'languageCode' => 'en-US',
    ]);
    

    and if you want Google Storage Client, then simply:

    $storage = new StorageClient([
       'projectId' => $projectId,
       'keyFilePath' => 'path/to/file.json',   
    ])
    

    If that doesn't help then try also

    Go to this link and use this code for connection to the bucket:

    function auth_cloud_explicit($projectId, $serviceAccountPath)
    {
        # Explicitly use service account credentials by specifying the private key
        # file.
        $config = [
            'keyFilePath' => $serviceAccountPath,
            'projectId' => $projectId,
        ];
        $storage = new StorageClient($config);
    
        # Make an authenticated API request (listing storage buckets)
        foreach ($storage->buckets() as $bucket) {
            printf('Bucket: %s' . PHP_EOL, $bucket->name());
        }
    }
    

    and also going to Google Cloud Platform / IAM and adding the service account that the code was giving an error that this account does not have an access to the bucket. Now everything is working fine! Thanks to @brandon-yarbrough for the help

    If none of the above works for you just try and setup the environment inside your file using this code:

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

    And this should work.