This topic describes how to perform CORS.

Cross-origin resource sharing (CORS) allows web applications to access resources that belong to another region. OSS provides CORS APIs for convenient cross-origin access control.

For more information, see Cross-origin resource sharing in OSS Developer Guide.

OSS CORS settings contain one or more CORS rules. Each CORS rule includes the following parameters:

  • allowed_origins: The origins allowed for cross-origin requests, for example, www.my-domain.com, *.
  • allowed_methods: The HTTP methods (PUT/POST/GET/DELETE/HEAD) allowed for cross-origin requests.
  • allowed_headers: The headers allowed in a prefetch command (OPTIONS), for example, x-oss-test, *.
  • expose_headers: The headers allowed for the user to access in the application.
  • max_age_seconds: The cache time for the returned result of a browser prefetch (OPTIONS) request to a specific resource.

Configure CORS rules

The following code uses Bucket#cors= to configure a CORS rule:

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  endpoint: 'endpoint',
  access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')

bucket = client.get_bucket('my-bucket')
bucket.cors = [
    CORSRule.new(
      :allowed_origins => ['aliyun.com', 'http://www.taobao.com'],
      :allowed_methods => ['PUT', 'POST', 'GET'],
      :allowed_headers => ['Authorization'],
      :expose_headers => ['x-oss-test'],
      :max_age_seconds => 100)
]

View CORS rules

The following code uses Bucket#cors to display CORS rules:

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  endpoint: 'endpoint',
  access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')

bucket = client.get_bucket('my-bucket')
cors = bucket.cors
puts cors.map(&:to_s)

Clear CORS rules

The following code uses Bucket#cors= to clear CORS rules:

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  endpoint: 'endpoint',
  access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')

bucket = client.get_bucket('my-bucket')
bucket.cors = []