El uso compartido de recursos de origen cruzado (CORS) permite que las aplicaciones web accedan a recursos de distintos orígenes. Object Storage Service (OSS) proporciona operaciones de API para CORS con el fin de controlar los permisos de acceso entre orígenes.
Precauciones
En este tema se utiliza el endpoint público de la región China (Hangzhou). Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para más información sobre las regiones y los endpoints compatibles, consulte Regions and endpoints.
Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Create an OssClient.
Para establecer reglas de CORS, necesita el permiso
oss:PutBucketCors. Para obtener reglas de CORS, necesita el permisooss:GetBucketCors. Para eliminar reglas de CORS, necesita el permisooss:DeleteBucketCors. Para más información, consulte Grant custom permissions to a RAM user.
Establecer reglas de CORS
A continuación se muestra un ejemplo de código para establecer las reglas de CORS del 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");
Obtener reglas de CORS
A continuación se muestra un ejemplo de código para obtener las reglas de CORS del 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;
}
Eliminar reglas de CORS
A continuación se muestra un ejemplo de código para eliminar todas las reglas de CORS del 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");
Referencias
Para consultar el código de ejemplo completo sobre la gestión de reglas de CORS, visite GitHub.
Para más información sobre la operación de API que permite configurar reglas de CORS, consulte PutBucketCors.
Para más información sobre la operación de API que permite consultar reglas de CORS, consulte GetBucketCors.
Para más información sobre la operación de API que permite eliminar reglas de CORS, consulte DeleteBucketCors.