Kenny Wyland
Kenny Wyland

Reputation: 21880

Unable to make gs:// file public to serve directly from Google Storage

I want to be able to serve image files directly from Google Storage. I'm following the code suggestion from Google, but I'm still getting Access Denied and Anonymous caller does not have storage.objects.get access. I'm running this in my Google App Engine project:

require_once 'vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use google\appengine\api\cloud_storage\CloudStorageTools;

$storage = new StorageClient();
$storage->registerStreamWrapper();

$text = "Contained text: ".date("Y-m-d H:i:s")."\n";

$options = ['gs' => ['acl' => 'public-read']];
$context = stream_context_create($options);
$filepath = "gs://$project.appspot.com/public_file.txt";
file_put_contents($filepath, $text, 0, $context);

$publicurl = CloudStorageTools::getPublicUrl($filepath, false);

The file is being successfully written to Google Storage. I've looked at it via the Storage Browser in the Cloud Console.

But when I try to browse to it, I get Access Denied. What am I missing?

enter image description here

$ gsutil acl get gs://my-app-project.appspot.com/public_file.txt

[
  {
    "entity": "project-owners-XXXXXXXXXXXX",
    "projectTeam": {
      "projectNumber": "XXXXXXXXXXXX",
      "team": "owners"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-editors-XXXXXXXXXXXX",
    "projectTeam": {
      "projectNumber": "XXXXXXXXXXXX",
      "team": "editors"
    },
    "role": "OWNER"
  },
  {
    "entity": "project-viewers-XXXXXXXXXXXX",
    "projectTeam": {
      "projectNumber": "XXXXXXXXXXXX",
      "team": "viewers"
    },
    "role": "READER"
  },
  {
    "email": "[email protected]",
    "entity": "[email protected]",
    "role": "OWNER"
  }
]

Upvotes: 1

Views: 655

Answers (1)

Kyle Humfeld
Kyle Humfeld

Reputation: 1907

I’m not sure why the code above isn’t working to set the permissions to public, but here is a workaround.

If you are using a bucket that can be entirely public, then what you can do is set the default ACL on the bucket to be public-read, then whenever you create files in that bucket they will already be public.

Here is where I got the command from: https://cloud.google.com/php/getting-started/using-cloud-storage

gsutil defacl set public-read gs://[YOUR-PROJECT-ID]

Upvotes: 2

Related Questions