هذه الصفحة غير متوفرة حاليًا بلغتك المحلية. نحن نعمل جاهدين على إضافة المزيد من اللغات. شاكرين تفهمك ودعمك المستمر لنا.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Configuring CORS for a Bucket

Updated on 2024-12-03 GMT+08:00
NOTICE:

If you have any questions during development, post them on the Issues page of GitHub. For details about parameters and usage of each API, see the API Reference.

OBS provides distributed storage service over HTTP/HTTPS, and stores data in buckets. However, browsers do not allow the cross-origin AJAX requests by default. For this reason, configure CORS before using the OBS BrowserJS SDK to access buckets. You can configure CORS on OBS Console, on OBS Browser, or using other OBS SDKs (excluding the OBS BrowserJS SDK). The following configuration is recommended for the CORS rule.

Parameter

Value

Description

Allowed Origin

*

Allows all request origins.

NOTE:

You can also configure a domain name or IP address.

Allowed Method

PUT, GET, POST, DELETE, and HEAD

Allows all HTTP methods.

Allowed Header

*

Allows requests to carry any headers.

Expose Header

  • ETag
  • x-obs-request-id
  • x-obs-api
  • Content-Type
  • Content-Length
  • Cache-Control
  • Content-Disposition
  • Content-Encoding
  • Content-Language
  • Expires
  • x-obs-id-2
  • x-reserved-indicator
  • x-obs-version-id
  • x-obs-copy-source-version-id
  • x-obs-storage-class
  • x-obs-delete-marker
  • x-obs-expiration
  • x-obs-website-redirect-location
  • x-obs-restore
  • x-obs-version
  • x-obs-object-type
  • x-obs-next-append-position

Allows the response to return the specified additional headers.

NOTICE:

This parameter specifies the additional headers that a browser can expose to the client.

Take ETag as an example. It is not a standard response header, so to obtain its value, you need to add it in this parameter for the browser to return the value in the response.

Configuring CORS on OBS Console

  1. Log in to OBS Console. In the bucket list, click the bucket you want. The bucket Overview page is displayed.

  2. In the Basic Configurations area, click CORS Rules. The CORS Rules page is displayed.
  3. Click Create. The Create CORS Rule dialog box is displayed. Set the parameters according to the preceding table. See the following figure.

  4. Click OK. On the CORS Rules page, view the configured rule.
NOTE:

The CORS configuration of a bucket takes effect in two minutes. You can access the bucket using the OBS BrowserJS SDK only after the configuration takes effect.

Configuring CORS Using the OBS Java SDK

You can call ObsClient.setBucketCors of the OBS Java SDK to configure the CORS rule for a bucket. The sample code is as follows:

// Replace the following region with the one in use. CN-Hong Kong is used here as an example.
String endPoint = "https://obs.ap-southeast-1.myhuaweicloud.com";
String ak = System.getenv("ACCESS_KEY_ID");
String sk = System.getenv("SECRET_ACCESS_KEY_ID");
// Create an ObsClient instance.
ObsClient obsClient = new ObsClient(ak, sk, endPoint);

BucketCors cors = new BucketCors();

List<BucketCorsRule> rules = new ArrayList<BucketCorsRule>();
BucketCorsRule rule = new BucketCorsRule();

// Specify the origin of the cross-origin request.
ArrayList<String> allowedOrigin = new ArrayList<String>();
allowedOrigin.add( "*");  
rule.setAllowedOrigin(allowedOrigin);

// Specify the methods of the cross-origin request.
ArrayList<String> allowedMethod = new ArrayList<String>();
allowedMethod.add("GET");  
allowedMethod.add("POST");
allowedMethod.add("PUT");
allowedMethod.add("DELETE");
allowedMethod.add("HEAD");
rule.setAllowedMethod(allowedMethod);

// Specify the headers of the cross-origin request.
ArrayList<String> allowedHeader = new ArrayList<String>();
allowedHeader.add("*"); 
rule.setAllowedHeader(allowedHeader);

// Specify the additional headers in the response to the cross-origin request.
ArrayList<String> exposeHeader = new ArrayList<String>();
exposeHeader.add("ETag");
exposeHeader.add("Content-Type");
exposeHeader.add("Content-Length");
exposeHeader.add("Cache-Control");
exposeHeader.add("Content-Disposition");
exposeHeader.add("Content-Encoding");
exposeHeader.add("Content-Language");
exposeHeader.add("Expires");
exposeHeader.add("x-obs-request-id");
exposeHeader.add("x-obs-id-2");
exposeHeader.add("x-reserved-indicator");
exposeHeader.add("x-obs-api");
exposeHeader.add("x-obs-version-id");
exposeHeader.add("x-obs-copy-source-version-id");
exposeHeader.add("x-obs-storage-class");
exposeHeader.add("x-obs-delete-marker");
exposeHeader.add("x-obs-expiration");
exposeHeader.add("x-obs-website-redirect-location");
exposeHeader.add("x-obs-restore");
exposeHeader.add("x-obs-version");
exposeHeader.add("x-obs-object-type");
exposeHeader.add("x-obs-next-append-position");
rule.setExposeHeader(exposeHeader);

rule.setMaxAgeSecond(100);
rules.add(rule);
cors.setRules(rules);

try
{
    obsClient.setBucketCors("bucketname", cors);
catch (ObsException e)
{
    System.out.println("HTTP Code: " + e.getResponseCode());
    System.out.println("Error Code:" + e.getErrorCode());
    System.out.println("Error Message: " + e.getErrorMessage());
    
    System.out.println("Request ID:" + e.getErrorRequestId());
    System.out.println("Host ID:" + e.getErrorHostId());
}
}

Configure CORS Using OBS Python SDK

You can call ObsClient.setBucketCors of the OBS Python SDK to configure the CORS of a bucket. The sample code is as follows:

# Import the module.
from obs import ObsClient

# Obtain an AK/SK pair using environment variables or import the AK/SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK/SK pair and a security token to access OBS, obtain them from environment variables.
security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. CN-Hong Kong is used here as an example. Replace it with the one in your actual situation.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK/SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)

from obs import CorsRule

# Specify the origin of the cross-origin request.
allowedOrigin = ['*']
# Specify the methods of the cross-origin request.
allowedMethod = ['PUT', 'POST', 'GET', 'DELETE', 'HEAD']
# Specify the headers of the cross-origin request.
allowedHeader = ['*']

# Specify the additional headers in the response to the cross-origin request.
exposeHeader = ['ETag', 'Content-Type', 'Content-Length', 'Cache-Control', 'Content-Disposition', 'Content-Encoding', 'Content-Language', 'Expires', 'x-obs-request-id', 'x-obs-id-2', 'x-reserved-indicator', 'x-obs-api', 'x-obs-version-id', 'x-obs-copy-source-version-id', 'x-obs-storage-class', 'x-obs-delete-marker', 'x-obs-expiration', 'x-obs-website-redirect-location', 'x-obs-restore', 'x-obs-version', 'x-obs-object-type', 'x-obs-next-append-position']

maxAgeSecond = 100
cors = CorsRule(id='rule1', allowedMethod=allowedMethod,                 
                 allowedOrigin=allowedOrigin, allowedHeader=allowedHeader,                 
                 maxAgeSecond=maxAgeSecond, exposeHeader=exposeHeader)

resp = obsClient.setBucketCors('bucketname', corsList=[cors])
if resp.status < 300:    
    print('requestId:', resp.requestId)
else:    
    print('errorCode:', resp.errorCode)    
    print('errorMessage:', resp.errorMessage)
NOTE:
  • Except the OBS BrowserJS SDK, all the other OBS SDKs can be used to configure CORS rules for buckets.
  • You can also configure CORS for a bucket by referring to Configuring CORS on OBS Console or the CORS rule configuration section in the SDK Developer Guide of a specific language.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback