Cross-origin resource sharing (CORS) lets web applications access resources from different origins. Object Storage Service (OSS) provides API operations for CORS to control permissions for cross-origin access.
Prerequisites
Before you begin, ensure that you have:
An OSS bucket
The required RAM permissions for the operation you want to perform:
Set CORS rules:
oss:PutBucketCorsRetrieve CORS rules:
oss:GetBucketCorsDelete CORS rules:
oss:DeleteBucketCors
For more information about granting permissions, see Grant custom permissions to a RAM user.
Usage notes
The examples in this topic use the public endpoint for the China (Hangzhou) region (
https://oss-cn-hangzhou.aliyuncs.com). To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For supported regions and endpoints, see Regions and endpoints.To create an OSSClient instance using a custom domain name or Security Token Service (STS), see Create an OSSClient instance.
CORS rule parameters
Each CORS rule maps to a set of HTTP response headers that OSS returns to the browser. The following table describes each parameter.
| Parameter | HTTP header controlled | Description | Constraints |
|---|---|---|---|
AllowedOrigin | Access-Control-Allow-Origin | The origins allowed to make cross-origin requests. Example: https://example.com:8080. To allow all origins, use *. | Multiple values allowed. Each value can contain at most one * wildcard. |
AllowedMethod | Access-Control-Allow-Methods | The HTTP methods allowed for cross-origin requests. Example: GET, POST, PUT. | Multiple values allowed. |
AllowedHeader | Access-Control-Allow-Headers | The request headers allowed in cross-origin requests. To allow all headers, use *. | Multiple values allowed. Each value can contain at most one * wildcard. |
ExposeHeader | Access-Control-Expose-Headers | The response headers that JavaScript in the browser can access. Example: x-oss-header. | Multiple values allowed. The * wildcard is not supported. |
MaxAgeSeconds | Access-Control-Max-Age | How long (in seconds) the browser caches the preflight (OPTIONS) response. | — |
Additional settings:
ResponseVary: Controls whether OSS returns theVary: Originheader. Set tofalseto never return this header.Maximum rules per bucket: 10. Calling
putBucketCorsoverwrites all existing rules.
Set CORS rules
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Model\CorsConfig;
use OSS\Model\CorsRule;
// Get access credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
$provider = new EnvironmentVariableCredentialsProvider();
// Replace with the endpoint for your bucket's region.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Replace with your bucket name.
$bucket = "examplebucket";
$corsConfig = new CorsConfig();
$rule = new CorsRule();
// AllowedHeader: request headers allowed in cross-origin requests.
// Use "*" to allow all headers. Each value can contain at most one "*".
$rule->addAllowedHeader("*");
// ExposeHeader: response headers that JavaScript can access.
// The "*" wildcard is not supported here.
$rule->addExposeHeader("x-oss-header");
// AllowedOrigin: origins allowed to make cross-origin requests.
// Each value can contain at most one "*". Use "*" to allow all origins.
$rule->addAllowedOrigin("https://example.com:8080");
$rule->addAllowedOrigin("https://*.aliyun.com");
// $rule->addAllowedOrigin("*"); // Allow all origins
// AllowedMethod: HTTP methods allowed for cross-origin requests.
$rule->addAllowedMethod("POST");
// MaxAgeSeconds: how long (in seconds) the browser caches the preflight response.
$rule->setMaxAgeSeconds(10);
// Each bucket supports a maximum of 10 rules.
$corsConfig->addRule($rule);
// Specify whether to return the Vary: Origin header. If this is set to false, the Vary: Origin header is never returned.
$corsConfig->setResponseVary(false);
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
// This call overwrites all existing CORS rules on the bucket.
$ossClient->putBucketCors($bucket, $corsConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");Get CORS rules
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;
try {
// Get access credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
$provider = new EnvironmentVariableCredentialsProvider();
// Replace with the endpoint for your bucket's region.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Replace with your bucket name.
$bucket = "examplebucket";
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
$corsConfig = $ossClient->getBucketCors($bucket);
if ($corsConfig->getResponseVary()) {
printf("Response Vary : true" . PHP_EOL);
} else {
printf("Response Vary : false" . PHP_EOL);
}
foreach ($corsConfig->getRules() as $key => $rule) {
if ($rule->getAllowedHeaders()) {
foreach ($rule->getAllowedHeaders() as $header) {
printf("Allowed Headers :" . $header . PHP_EOL);
}
}
if ($rule->getAllowedMethods()) {
foreach ($rule->getAllowedMethods() as $method) {
printf("Allowed Methods :" . $method . PHP_EOL);
}
}
if ($rule->getAllowedOrigins()) {
foreach ($rule->getAllowedOrigins() as $origin) {
printf("Allowed Origins :" . $origin, PHP_EOL);
}
}
if ($rule->getExposeHeaders()) {
foreach ($rule->getExposeHeaders() as $exposeHeader) {
printf("Expose Headers :" . $exposeHeader . PHP_EOL);
}
}
printf("Max Age Seconds :" . $rule->getMaxAgeSeconds() . PHP_EOL);
}
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}Delete CORS rules
Deleting CORS rules removes all rules from the bucket. There is no way to delete individual rules.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
// Get access credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this code.
$provider = new EnvironmentVariableCredentialsProvider();
// Replace with the endpoint for your bucket's region.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Replace with your bucket name.
$bucket = "examplebucket";
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region" => "cn-hangzhou"
);
$ossClient = new OssClient($config);
$ossClient->deleteBucketCors($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");What's next
For the complete sample code, see GitHub.
For API details, see PutBucketCors, GetBucketCors, and DeleteBucketCors.