Google Cloud Storage CORS

Share on:

Introduction

When working with Google Cloud Storage as a backend, you will probably need to amend the CORS setting at some point. CORS stands for Cross Origin Resource Sharing and is invoked from your browser as a security access feature. Typically the HTTP-header will indicate which origin is permitted to be accessed. If you want to work with the web and specifically image files, adding a CORS setting will save you time.

CORS Support

In most cases, an XML endpoint will be used to access information in a storage bucket. XML API will restrict access based on CORS configuration, requiring a CORS configuration to be applied if accessed via a Browser. Cloud Storage supports two XML endpoints for objects

  • storage.googleapis.com/[BUCKETNAME]
  • [BUCKETNAME].storage.google.com

In both instances, you should prefix the storage object with the above endpoint to access the item.

CORS Settings File

On Google Cloud a CORS file can be applied to a storage bucket to indicate how to handle access. The settings file is formatted as JSON and contains information on what is permitted.

1[{"origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600}]
  1. Create a file named cors-config.json
  2. Add the following json to the file:
 1[
 2  {
 3    "origin": [
 4      "*"
 5    ],
 6    "method": [
 7      "GET"
 8    ],
 9    "maxAgeSeconds": 3600
10  }
11]

The above configuration includes the following settings:

Field Value Description
origin * Set to where access can be performed. * represents an ALL wildcard
method GET Represents the HTTP verb (GET
maxAgeSeconds 3600 The max age before a pre-flight request is repeated

Adding the above to a storage bucket will allow a HTTP GET operation to be performed from any domain. If you wish you can restrict the origin to a specific domain e.g. localhost, richrose.dev if you wish. Expanding the HTTP Verbs is also allowed to bring the flexibility that other platforms take for granted.

CORS Apply

Adding the CORS setting to Cloud Storage is done at the bucket level

1gsutil cors set cors-config.json gs://[BUCKETNAME]

You can review the CORS setting for a bucket by doing the following:

1gsutil cors get gs://[BUCKETNAME]

To learn more about adding CORS settings on Google Cloud use the link below: