Debido a la política de mismo origen de los navegadores, las solicitudes de origen cruzado pueden rechazarse al intercambiar datos o compartir recursos entre distintos nombres de dominio. Para resolver este problema, configure reglas de uso compartido de recursos de origen cruzado (CORS). En estas reglas, especifique los nombres de dominio desde los cuales se pueden enviar solicitudes, los métodos permitidos para enviarlas y los encabezados autorizados.
Notas
En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.
En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.
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 Configure a client (Go SDK V1).
Para configurar reglas CORS, debe tener el permiso oss:PutBucketCors. Para consultar reglas CORS, debe tener el permiso oss:GetBucketCors. Para eliminar reglas CORS, debe tener el permiso oss:DeleteBucketCors. Para obtener más información, consulte Grant a custom policy.
Código de ejemplo
Set CORS rules
El siguiente código de ejemplo muestra cómo configurar una regla CORS para un bucket específico:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Set bucketName to the name of your bucket.
bucketName := "yourBucketName"
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error creating credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
isTrue := true
rule1 := oss.CORSRule{
AllowedOrigin: []string{"*"},
AllowedMethod: []string{"PUT", "GET", "POST"},
AllowedHeader: []string{},
ExposeHeader: []string{},
MaxAgeSeconds: 100,
}
rule2 := oss.CORSRule{
AllowedOrigin: []string{"http://www.a.com", "http://www.b.com"},
AllowedMethod: []string{"GET"},
AllowedHeader: []string{"Authorization"},
ExposeHeader: []string{"x-oss-test-01", "x-oss-test-02"},
MaxAgeSeconds: 100,
}
put := oss.PutBucketCORS{}
put.CORSRules = []oss.CORSRule{rule1, rule2}
put.ResponseVary = &isTrue
// Set the CORS rules.
err = client.SetBucketCORSV2(bucketName, put)
if err != nil {
log.Fatalf("Error setting CORS rules: %v", err)
}
log.Println("Set Success")
}
Get CORS rules
El siguiente código de ejemplo muestra cómo consultar las reglas CORS de un bucket específico:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Set bucketName to the name of your bucket.
bucketName := "yourBucketName"
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error creating credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// Get the CORS rules.
corsRes, err := client.GetBucketCORS(bucketName)
if err != nil {
log.Fatalf("Error getting CORS rules: %v", err)
}
// Print the CORS rules.
for _, rule := range corsRes.CORSRules {
log.Printf("Cors Rules Allowed Origin: %v", rule.AllowedOrigin)
log.Printf("Cors Rules Allowed Method: %v", rule.AllowedMethod)
log.Printf("Cors Rules Allowed Header: %v", rule.AllowedHeader)
log.Printf("Cors Rules Expose Header: %v", rule.ExposeHeader)
log.Printf("Cors Rules Max Age Seconds: %d", rule.MaxAgeSeconds)
}
if corsRes.ResponseVary != nil {
log.Printf("Cors Rules Response Vary: %t", *corsRes.ResponseVary)
}
}
Delete CORS rules
El siguiente código de ejemplo muestra cómo eliminar todas las reglas CORS de un bucket específico:
package main
import (
"log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
log.Fatalf("Error creating credentials provider: %v", err)
}
// Create an OSSClient instance.
// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual Endpoint.
// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
clientOptions = append(clientOptions, oss.Region("yourRegion"))
// Set the signature version.
clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
client, err := oss.New("yourEndpoint", "", "", clientOptions...)
if err != nil {
log.Fatalf("Error creating OSS client: %v", err)
}
// Set bucketName to the name of the bucket, for example, examplebucket.
bucketName := "examplebucket"
// Delete the CORS rules.
err = client.DeleteBucketCORS(bucketName)
if err != nil {
log.Fatalf("Error deleting CORS rules: %v", err)
}
log.Println("Delete Bucket CORS Success")
}
Referencias
Para ver el código de ejemplo completo sobre CORS, consulte Ejemplo en GitHub.
Para obtener más información sobre la operación de API usada para establecer reglas CORS, consulte SetBucketCORSV2.
Para obtener más información sobre la operación de API usada para obtener reglas CORS, consulte GetBucketCORS.
Para obtener más información sobre la operación de API usada para eliminar reglas CORS, consulte DeleteBucketCORS.