edit-icon download-icon

CORS

Last Updated: Nov 06, 2017

Cross-origin Resource Sharing (CORS) allows web applications to access resources in other domains. OSS provides an interface for developers to conveniently control cross-origin access permissions. For more information, see Cross-origin resource sharing.

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 results of a browser prefetch (OPTIONS) request for a specified resource.

Configure CORS rules

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

  1. require 'aliyun/oss'
  2. client = Aliyun::OSS::Client.new(
  3. endpoint: 'endpoint',
  4. access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')
  5. bucket = client.get_bucket('my-bucket')
  6. bucket.cors = [
  7. CORSRule.new(
  8. :allowed_origins => ['aliyun.com', 'http://www.taobao.com'],
  9. :allowed_methods => ['PUT', 'POST', 'GET'],
  10. :allowed_headers => ['Authorization'],
  11. :expose_headers => ['x-oss-test'],
  12. :max_age_seconds => 100)
  13. ]

View CORS rules

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

  1. require 'aliyun/oss'
  2. client = Aliyun::OSS::Client.new(
  3. endpoint: 'endpoint',
  4. access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')
  5. bucket = client.get_bucket('my-bucket')
  6. cors = bucket.cors
  7. puts cors.map(&:to_s)

Clear CORS rules

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

  1. require 'aliyun/oss'
  2. client = Aliyun::OSS::Client.new(
  3. endpoint: 'endpoint',
  4. access_key_id: 'AccessKeyId', access_key_secret: 'AccessKeySecret')
  5. bucket = client.get_bucket('my-bucket')
  6. bucket.cors = []
Thank you! We've received your feedback.