跨域资源共享(Cross-origin resource sharing,简称CORS)允许Web端的应用程序访问不属于本域的资源。OSS提供跨域资源共享接口,方便您控制跨域访问的权限。本文介绍如何进行跨域资源共享。
更多关于跨域资源共享的介绍,请参见开发指南中的设置跨域访问和API参考中PutBucketcors。
OSS的跨域共享设置由一条或多条CORS规则组成,每条CORS规则包含以下设置:
- allowed_origins,允许的跨域请求的来源,例如example.com, *
- allowed_methods,允许的跨域请求的HTTP方法(PUT、POST、GET、DELETE、HEAD)
- allowed_headers,在OPTIONS预取指令中允许的header,如x-oss-test, *
- expose_headers,允许用户从应用程序中访问的响应头
- max_age_seconds,浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间
设置CORS规则
通过bucket.cors
设置CORS规则:
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 => ['http://example.com', 'http://example.net'], :allowed_methods => ['PUT', 'POST', 'GET'], :allowed_headers => ['Authorization'], :expose_headers => ['x-oss-test'], :max_age_seconds => 100) ]
查看CORS规则
通过bucket.cors
查看CORS规则:
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)
清空CORS规则
通过bucket.cors
清空CORS规则:
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 = []