Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 981
Dimitar Avatar asked Feb 20 '18 08:02

Dimitar


People also ask

How do I authenticate Google Cloud Storage?

API authenticationIn the OAuth 2.0 Playground, click Cloud Storage API v1, and then select an access level for your application ( full_control , read_only , or read_write ). Click Authorize APIs. Sign in to your Google account when prompted. In the dialogue that appears, click Allow.

Where are Google Cloud credentials stored?

When gsutil is installed/used via the Cloud SDK ("gcloud"), credentials are stored by Cloud SDK in a non-user-editable file located under ~/. config/gcloud (any manipulation of credentials should be done via the gcloud auth command).

What is needed for GCP API?

To use Google Cloud APIs in your applications, you first need to have a Google account. This allows you to use Google developer products, including Google Cloud console, gcloud CLI, Cloud Logging, and Cloud Monitoring.


2 Answers

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

UPDATE: 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.

Also as of 12.2018 there is a updated code you can use which is:

use Google\Auth\Credentials\GCECredentials;

$gceCredentials = new GCECredentials();
$config = [
    'projectId' => $projectId,
    'credentialsFetcher' => $gceCredentials,
];
like image 140
Dimitar Avatar answered Sep 29 '22 08:09

Dimitar


require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;       
 $storage = new StorageClient([
        'keyFilePath' => 'path/key.json',
        'projectId' => 'you_projectid'
    ]);
    $bucket = $storage->bucket('namebucket');
    $bucket->upload(
        fopen('data/demo.txt', 'r')
    );
like image 44
Mau Xanh Cua Linh Avatar answered Sep 29 '22 09:09

Mau Xanh Cua Linh