Skip to main content

CORS Settings

Security Source configuration is the core security mechanism of CloudBase services, ensuring only authorized sources can access your CloudBase resources through strict access control. This article details how to configure and manage Web security domains and mobile application security sources.

CORS configuration works at two levels: the security domain allowlist decides which domains may call your resources, and route-level CORS validation decides whether the HTTP Gateway handles cross-origin requests for a given route.

Security Domain Configuration​

What Is a Security Domain?​

Security Domain is an access control mechanism that ensures only domains on the allowlist can access CloudBase resources, effectively preventing unauthorized access.

Configuration Method​

Console Operation Steps​

  1. Log in to CloudBase console / HTTP Gateway / CORS Settings
  2. In the "Security Domain" section, click the [Add Domain] button.
  3. In the pop-up dialog box, fill in the domain name to be authorized:
    • Supports full domain names (e.g., www.example.com)
    • Supports wildcards (e.g., *.example.com)
    • Supports port numbers (e.g., example.com:8080)
  4. Click [OK] to complete the addition

Configuration Example​

# Allow All Subdomains
*.example.com

# Allow Specific Domain Names
www.example.com

# Allow Domain Names with Ports
localhost:3000

Notes​

  • Quota Limit: Each environment can configure up to 50 secure domains.
  • Effective Time: Takes effect approximately 1-2 minutes after configuration
  • Format Requirement: Do not include the protocol prefix (e.g., https://)
  • Default Secure Domains: The system automatically configures the following domains:
    • localhost - Local development and debugging
    • env-id.<your-env-region>.app.tcloudbase.com - HTTP Gateway
    • env-id.tcb.qcloud.la - File Storage Service
    • env-id.tcloudbaseapp.com - Static Website Hosting Service (requires activation)

Troubleshooting Common Issues​

Why is the domain name still inaccessible after configuration?

Please check the following points:

  1. Whether the domain name is spelled correctly (including case sensitivity)
  2. Whether the protocol prefix (e.g., https://) has been incorrectly included
  3. Whether it is accessed within an iframe (requires adding a special tag after the secure domain)
  4. Whether sufficient effective time has been waited (1-2 minutes)
  5. Whether there are any relevant error messages in the browser console

Route-Level CORS Validation​

CORS validation controls cross-origin requests initiated by browsers. When enabled, the HTTP Gateway validates the request origin at the gateway level and only allows origins in the security domain allowlist.

How It Works​

  • CORS validation enabled: the HTTP Gateway handles cross-origin requests at the gateway level

    • Validates whether the request origin domain is in the web security domain allowlist
    • Automatically adds CORS response headers (such as Access-Control-Allow-Origin)
    • Blocks cross-origin requests that are not in the allowlist
  • CORS validation disabled: cross-origin requests are forwarded to backend resources directly

    • The gateway performs no CORS validation and adds no response headers
    • Backend services (cloud functions / CloudBase Run) must handle CORS themselves
    • Suitable when you need flexible control over CORS policies

Use Cases​

If your frontend application (website, single-page application, etc.) needs to call cloud functions or CloudBase Run services directly, enable CORS validation:

// Frontend example - callable directly with CORS validation enabled
fetch('https://your-env.<your-env-region>.app.tcloudbase.com/api/getData', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log('Data fetched successfully:', data))
.catch(error => console.error('Request failed:', error));

Advantages:

  • The gateway handles CORS automatically, so backend code does not deal with CORS logic
  • Unified security domain management that is easy to maintain
  • Less backend code complexity

Scenario 2: Backend Custom CORS Policy (Disable CORS Validation)​

To implement a more flexible CORS policy in your backend, disable CORS validation:

// Cloud function example - handle CORS yourself with validation disabled
exports.main = async (event, context) => {
// Get request origin
const origin = event.headers.origin || event.headers.Origin;

// Custom CORS logic
const allowedOrigins = ['https://example.com', 'https://app.example.com'];
const corsHeaders = {};

if (allowedOrigins.includes(origin)) {
corsHeaders['Access-Control-Allow-Origin'] = origin;
corsHeaders['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
corsHeaders['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';
corsHeaders['Access-Control-Allow-Credentials'] = 'true';
}

// Handle OPTIONS preflight request
if (event.httpMethod === 'OPTIONS') {
return {
statusCode: 204,
headers: corsHeaders,
body: ''
};
}

// Business logic
const result = {
message: 'Request successful',
data: { /* business data */ }
};

return {
statusCode: 200,
headers: {
...corsHeaders,
'Content-Type': 'application/json'
},
body: JSON.stringify(result)
};
};

Applicable scenarios:

  • Different CORS policies for different endpoints
  • Dynamic decisions on whether to allow cross-origin requests
  • Complex CORS response headers (such as Credentials, Expose-Headers, and more)

CORS Troubleshooting​

If you encounter CORS errors, troubleshoot in this order:

  1. Check the CORS validation switch

    • If enabled, confirm the request origin is in the security domain allowlist
    • If disabled, confirm the backend handles CORS requests correctly
  2. Verify the domain configuration

    • Domains must match completely, including protocol and port
    • Wildcard domains must be formatted correctly (e.g., *.example.com)
  3. Check the browser console

    • Read the specific CORS error message
    • Confirm whether the OPTIONS preflight request succeeds

Relationship with Authentication​

CORS validation and Authentication are two independent security mechanisms:

  • CORS validation: controls which domains can initiate requests
  • Authentication: controls which users can access resources

Both can be enabled together for defense in depth.

Mobile App Security Source​

Why Mobile Application Security Sources Need to Be Configured​

Mobile application security sources prevent your cloud resources from being accessed by unauthorized applications, effectively protecting your data security and business logic.

Configuration Process​

Console Operation Steps​

  1. On the [Security Sources] configuration page, click [Add Application]

  2. Fill in the application information

    • Application Name: A name for easy identification (e.g., "MyApp-iOS-Production")

    • Application Identifier:

      • iOS applications: Use Bundle ID (e.g., com.example.myapp)
      • Android applications: use the application package name (e.g., com.example.myapp)
      • Mini Program: use AppID (e.g., wx1234567890)
  3. Click [Save] to complete the configuration

Obtaining and Using Application Credentials​

  1. In the actions column of the added application, click [Obtain Credentials]
  2. The system generates and displays environment information
  3. Click [Copy] to save private key information

Security Notice:

  • Private key information is highly sensitive and should not be hardcoded or stored in plain text
  • It is recommended to use secure storage mechanisms or remote configuration to obtain credentials
  • Regularly rotate application credentials
  • Different credentials should be used for different environments (development, testing, production)

Best Practices​

Security Policy​

  1. Principle of Least Privilege: Grant permissions only to necessary domains and applications
  2. Environment Isolation: Testing environment and production environment use different configurations
  3. Platform Differentiation: Create independent configurations for iOS, Android, and Mini Programs
  4. Version Control: Rotate application credentials during major version updates

Credential Management​

  • Use Key Management System (KMS) to store sensitive credentials
  • Credentials used by departing employees should be revoked immediately
  • Use CI/CD pipelines to automatically inject credentials and avoid manual operations

Monitoring and Auditing​

  • Configure abnormal access alarm rules (e.g., abnormal geolocation, sudden surge in access volume)
  • Monitor API call source distribution and frequency
  • Regularly audit security source configuration
  • Enable access logs and regularly analyze them

Configuration Checklist​

  • Is access to unnecessary domains and applications restricted
  • Are development, testing, and production environments separated
  • Are credentials rotated regularly (3-6 months)
  • Have obsolete configurations and unused credentials been removed
  • Has a monitoring and alarm mechanism been configured
  • Is there an emergency response process for credential leakage established

Frequently Asked Questions​

What to do in case of credential leakage?

If credential leakage is discovered, please immediately follow the procedure below:

  1. Immediately generate new credentials in the console
  2. Update the application code and release a new version
  3. Revoke the old credentials in the console
  4. Check the CloudBase logs to investigate abnormal access