O compartilhamento de recursos de origem cruzada (CORS) permite que aplicações web acessem recursos de diferentes origens. O Object Storage Service (OSS) oferece operações de API para CORS, permitindo controlar as permissões de acesso entre origens.
Precauções
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints suportados, consulte Regiões e endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Criar um OssClient.
Para definir regras de CORS, você precisa da permissão
oss:PutBucketCors. Para recuperar regras de CORS, é necessária a permissãooss:GetBucketCors. Já para excluir regras de CORS, requer-se a permissãooss:DeleteBucketCors. Para mais informações, consulte Conceder permissões personalizadas a um usuário RAM.
Definir regras de CORS
O código a seguir exemplifica como definir as regras de CORS para o bucket examplebucket.
<?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. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint to the Endpoint of your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Set bucket to the name of your bucket, for example, examplebucket.
$bucket= "examplebucket";
$corsConfig = new CorsConfig();
$rule = new CorsRule();
// Set the allowed response headers for cross-origin requests. You can set multiple AllowedHeader values. Each value can contain at most one asterisk (*) wildcard character.
// Set AllowedHeader to an asterisk (*) if you have no special requirements.
$rule->addAllowedHeader("*");
// Set the response headers that users can access from the application. You can set multiple ExposeHeader values. The asterisk (*) wildcard character is not supported in ExposeHeader.
$rule->addExposeHeader("x-oss-header");
// Set the allowed origins for cross-origin requests. You can set multiple AllowedOrigin values. Each value can contain at most one asterisk (*) wildcard character.
$rule->addAllowedOrigin("https://example.com:8080");
$rule->addAllowedOrigin("https://*.aliyun.com");
// To allow requests from all origins, set AllowedOrigin to an asterisk (*).
//$rule->addAllowedOrigin("*");
// Set the allowed methods for cross-origin requests.
$rule->addAllowedMethod("POST");
// Set the cache duration for the response to a preflight (OPTIONS) request. The unit is seconds.
$rule->setMaxAgeSeconds(10);
// A maximum of 10 rules can be added to each bucket.
$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);
// Existing rules are overwritten.
$ossClient->putBucketCors($bucket, $corsConfig);
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
Obter regras de CORS
O exemplo abaixo mostra como recuperar as regras de CORS do bucket examplebucket.
<?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 and save them in the provider. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint to the Endpoint of your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// Set bucket to the name of your bucket, for example, examplebucket.
$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;
}
Excluir regras de CORS
Utilize o código a seguir para excluir todas as regras de CORS do bucket examplebucket.
<?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. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Set endpoint to the Endpoint of your bucket's region. For example, if your bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Set bucket to the name of your bucket, for example, examplebucket.
$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");
Referências
Para visualizar o código de exemplo completo sobre gerenciamento de regras de CORS, consulte o GitHub.
Para mais detalhes sobre a operação de API usada para configurar regras de CORS, consulte PutBucketCors.
Para obter informações sobre a operação de API de consulta de regras de CORS, consulte GetBucketCors.
Caso precise excluir regras de CORS via API, consulte a documentação do DeleteBucketCors.