Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

com.google.cloud.storage.StorageException: 401 Unauthorized

I am trying to get this sample working without success

I installed and initialized the client:

export CLOUD_SDK_REPO="cloud-sdk-$(lsb_release -c -s)"

echo "deb https://packages.cloud.google.com/apt $CLOUD_SDK_REPO main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

sudo apt-get update \
    && sudo apt-get -y install google-cloud-sdk \
    && sudo apt-get -y install google-cloud-sdk-app-engine-java \
    && sudo apt-get -y install google-cloud-sdk-app-engine-python \

gcloud init

Then I authenticated successfully:

gcloud auth activate-service-account [email protected] --key-file=DockerStorage-e7def0adcafb.json

Then I tried the quick start sample:

Storage storage = StorageOptions.getDefaultInstance().getService();
String bucketName = "my-first-bucket";  // "my-new-bucket";
Bucket bucket = storage.create(BucketInfo.of(bucketName));
System.out.printf("Bucket %s created.%n", bucket.getName());

BOOM unauthorized

Exception in thread "main" com.google.cloud.storage.StorageException: 401 Unauthorized

What did I miss?

like image 523
javapenguin Avatar asked May 06 '26 14:05

javapenguin


1 Answers

At first, You have to a generate a Service account credential.

Generating a service account credential To generate a private key in JSON or PKCS12 format:

  1. Open the list of credentials in the Google Cloud Platform Console. Google Cloud Platform Console
  2. Click Create credentials.
  3. Select Service account key.
  4. A Create service account key window opens.
  5. Click the drop-down box below Service account, then click New service account.
  6. Enter a name for the service account in Name.
  7. Use the default Service account ID or generate a different one.
  8. Select the Key type: JSON or P12.
  9. Click Create.

Then simply use the credential json file in you code.

    StorageOptions storageOptions = StorageOptions.newBuilder()
       .setProjectId("YOUR_PROJECT_ID")
        .setCredentials(GoogleCredentials.fromStream(new 
         FileInputStream("path/YOUR_SERVICE_ACCOUNT_CRENDENTIAL.json"))).build();
    Storage storage = storageOptions.getService();
like image 83
fahad_sust Avatar answered May 09 '26 05:05

fahad_sust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!