Cross-origin resource sharing (CORS) is a standard cross-origin solution provided by HTML5. OSS uses the CORS standard for cross-origin access. You can use the PutBucketcors API of OSS to set CORS rules.
|Console||Web application, which is intuitive and easy to use|
|Java SDK||SDK demos in various languages|
Cross-origin access is commonly used in actual scenarios.
CORS is implemented as follows:
- If CORS is enabled, an HTTP request contains the Origin field in its header to specify the origin. In the previous example, the Origin field is set to www.a.com.
- After receiving the request, the server determines whether to allow the request from the origin based on CORS rules. If the request is allowed, the server includes the Access-Control-Allow-Origin field whose value is www.a.com in the response header, indicating that this cross-origin access is allowed. If the server allows all cross-origin requests, it includes the Access-Control-Allow-Origin field whose value is an asterisk (*) in the response header.
- The browser checks whether the Access-Control-Allow-Origin field is returned in the response header to determine whether the cross-origin request is allowed. If this field is not returned, the browser blocks the request. If the request is not a simple one, the browser first sends an OPTIONS request to obtain the CORS configuration of the server. If the server does not allow subsequent CORS operations, the browser blocks subsequent not-so-simple requests.
OSS allows you to set CORS rules so as to determine whether to allow or reject cross-origin requests as needed. You can set CORS rules at the bucket level. For more information, see PutBucketcors.
- Browsers automatically include CORS-related header fields. You do not need to perform other operations. CORS operations are applicable only to browsers.
- Whether a CORS request is allowed is completely independent of OSS authentication. OSS uses CORS rules only to determine whether CORS-related header fields are included. Browsers determine whether to block such a request.
- Before sending cross-origin requests, you must ensure that the cache feature is disabled for browsers. For example, two Webpages in the same browser, one originated from www.a.com and the other from www.b.com, send a request for the same cross-origin resource simultaneously. If the server receives the request from www.a.com first, it returns the resource with the Access-Control-Allow-Origin field whose value is www.a.com in the response header. When the server receives the request from www.b.com later, the browser returns the cached resource with the Access-Control-Allow-Origin field whose value is www.a.com in the response header. Because the response header field value does not match CORS rules for the request from www.b.com, this request fails.
To troubleshoot common errors, see OSS CORS errors and troubleshooting.