All Products
Search
Document Center

Object Storage Service:OSS C++ SDK V2

Last Updated:Jun 08, 2026

Use the OSS C++ SDK V2 to upload, download, and manage objects in Alibaba Cloud OSS from C++ applications. Built for high-performance scenarios, embedded systems, and desktop applications.

Note

The OSS C++ SDK V2 is in preview. Interfaces may change. Check the GitHub repository release notes for updates.

GitHub | sample code | migration guide | deepwiki

Quick start

Complete the following steps to install the SDK, configure credentials, and initialize a client.

Prerequisites

  • A C++17 or later compiler (GCC 7+, Clang 5+, or MSVC 2017+).

  • CMake 3.15 or later.

Run the cmake --version command to check your CMake version. If CMake is not installed or the version is earlier than 3.15, download and install CMake.

Install SDK

vcpkg is the recommended installation method.

vcpkg

Use the vcpkg package manager to install the SDK:

vcpkg install alibabacloud-oss-cpp-sdk-v2[curl]

# On Windows, you can use WinHTTP as the HTTP transport layer instead.
vcpkg install alibabacloud-oss-cpp-sdk-v2[winhttp]

You can also install from source code by using an overlay port:

git clone https://github.com/aliyun/alibabacloud-oss-cpp-sdk-v2.git
vcpkg install alibabacloud-oss-cpp-sdk-v2[curl] --overlay-ports=alibabacloud-oss-cpp-sdk-v2/vcpkg --head
Note

You must specify an HTTP transport layer (curl or winhttp), as none is enabled by default. You can enable both.

If both openssl and mbedtls are enabled, openssl takes precedence.

Optional features:

Feature

Description

curl

An HTTP transport layer based on libcurl. You must explicitly specify [curl] in the installation command, as this feature is not enabled by default.

winhttp

An HTTP transport layer based on WinHTTP (Windows only).

openssl

Uses OpenSSL for hash calculation.

mbedtls

Uses mbedTLS for hash calculation.

encryption

Enables client-side encryption. On non-Windows platforms, you must also enable openssl or mbedtls.

rtti

Enables runtime type information (RTTI) at compile time.

Complete definitions: vcpkg/vcpkg.json.

Source code

Download the latest version of the OSS C++ SDK V2 from GitHub, then build and install it with CMake:

git clone https://github.com/aliyun/alibabacloud-oss-cpp-sdk-v2.git
cd alibabacloud-oss-cpp-sdk-v2
mkdir build && cd build
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local
cmake --build . --target install

Available CMake options:

Option

Description

BUILD_SHARED_LIBS

Builds the SDK as a shared library. By default, a static library is built (OFF).

USE_CURL_TRANSPORT

Uses libcurl as the HTTP transport layer.

USE_WINHTTP_TRANSPORT

Uses WinHTTP as the HTTP transport layer (Windows only).

USE_SYSTEM_CURL

Uses the system-installed libcurl instead of the version included with the SDK.

USE_SYSTEM_OPENSSL

Uses the system-installed OpenSSL.

USE_SYSTEM_MBEDTLS

Uses the system-installed mbedTLS.

USE_STD_EXPECTED

Uses std::expected from the C++23 standard. By default, the compatible implementation included with the SDK is used.

ENABLE_ENCRYPTION

Enables client-side encryption.

ENABLE_RTTI

Enables runtime type information (RTTI).

Add the dependency to your project's CMakeLists.txt file:

cmake_minimum_required(VERSION 3.15)
project(my-app)

find_package(alibabacloud_oss_v2 REQUIRED)

add_executable(MyApp main.cpp)
target_link_libraries(MyApp PRIVATE alibabacloud_oss_v2::oss)

Configure access credentials

Set environment variables with your RAM user's AccessKey pair.

In the RAM console, create a RAM user and generate a permanent AccessKey. Save the AccessKey, and then grant the AliyunOSSFullAccess permission to the user.

Linux

  1. In the command-line interface, run the following commands to add the environment variables to your ~/.bashrc file.

    echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
    echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    1. Run the following command to apply the changes.

      source ~/.bashrc
    2. Run the following commands to verify that the environment variables are set.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

macOS

  1. In the terminal, run the following command to check your default shell.

    echo $SHELL
    1. The following steps depend on your default shell.

      Zsh

      1. Run the following commands to add the environment variables to your ~/.zshrc file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Run the following command to apply the changes.

        source ~/.zshrc
      3. Run the following commands to verify that the environment variables are set.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Run the following commands to add the environment variables to your ~/.bash_profile file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Run the following command to apply the changes.

        source ~/.bash_profile
      3. Run the following commands to verify that the environment variables are set.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

Windows

Command Prompt

  1. In Command Prompt (CMD), run the following commands:

    setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
    setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
  2. Reopen Command Prompt and run the following commands to verify that the environment variables are set.

    echo %OSS_ACCESS_KEY_ID%
    echo %OSS_ACCESS_KEY_SECRET%

PowerShell

  1. In PowerShell, run the following commands.

    [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User)
    [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'YOUR_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User)
  2. Reopen PowerShell and run the following commands to verify that the environment variables are set.

    [System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User)
    [System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User)

Initialize client

The SDK supports three request modes: OSSClient (synchronous), OSSClient (asynchronous) (thread-pool-based), and OSSAsyncClient (asynchronous) (native async). The following examples use ListBuckets to demonstrate each mode.

OSSClient (synchronous)

Use the OSSClient synchronous mode when you need to wait for an operation to complete before proceeding.

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as ap-southeast-1.
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();

    oss::OSSClient client(conf);

    auto outcome = client.listBuckets(
        oss::models::ListBucketsRequest());

    if (!outcome.has_value()) {
        auto& err = outcome.error();
        std::cerr << "Error Code: " << err.getCode() << std::endl;
        std::cerr << "Error Message: " << err.getMessage() << std::endl;
        std::cerr << "Request ID: " << err.getRequestId() << std::endl;
        return 1;
    }

    auto& result = outcome.value();
    for (auto& bucket : result.getBuckets()) {
        std::cout << "bucket: name:" << bucket.name
                  << ", region:" << bucket.region
                  << ", storageClass:" << bucket.storageClass
                  << std::endl;
    }

    return 0;
}

OSSClient (asynchronous)

This thread-pool-based asynchronous mode still uses OSSClient. After setting conf.executor (a thread pool), you call asyncCall() to dispatch a synchronous request to the thread pool for concurrent execution. The call returns a std::future, and the caller waits for the result with get().

If conf.executor is not set, asyncCall() returns a NoExecutor error.
#include <future>
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
#include "alibabacloud/oss2/utils/DefaultExecutor.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
    // Key: Configure a thread pool to enable asyncCall() support for OSSClient.
    conf.executor = std::make_shared<oss::DefaultExecutor>();

    oss::OSSClient client(conf);

    // Asynchronous call that returns a std::future.
    auto future = client.asyncCall(oss::models::ListBucketsRequest());

    // Wait for the result by using get() (future pattern).
    auto outcome = future.get();
    if (!outcome.has_value()) {
        auto& err = outcome.error();
        std::cerr << "Error Code: " << err.getCode() << std::endl;
        std::cerr << "Error Message: " << err.getMessage() << std::endl;
        return 1;
    }

    auto& result = outcome.value();
    for (auto& bucket : result.getBuckets()) {
        std::cout << "bucket: name:" << bucket.name
                  << ", region:" << bucket.region << std::endl;
    }
    return 0;
}

Concurrent upload and download examples: AsyncCallOnSyncClient.cpp and AsyncCallbackOnSyncClient.cpp.

OSSAsyncClient (asynchronous)

This native asynchronous mode uses OSSAsyncClient. Each operation has a corresponding operationNameAsync() method that receives the result through a callback, eliminating the need to configure a thread pool. This mode is ideal for scenarios that require a high volume of concurrent operations.

Before you run the sample code, replace <region-id> with an actual region and endpoint, such as ap-southeast-1.
#include <iostream>
#include <thread>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSAsyncClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();

    auto client = std::make_shared<oss::OSSAsyncClient>(conf);

    client->listBucketsAsync(
        oss::models::ListBucketsRequest(),
        oss::ListBucketsAsyncCallback([](oss::ListBucketsOutcome outcome) {
            if (!outcome.has_value()) {
                auto& err = outcome.error();
                std::cerr << "Error Code: " << err.getCode() << std::endl;
                std::cerr << "Error Message: " << err.getMessage() << std::endl;
                return;
            }

            auto& result = outcome.value();
            for (auto& bucket : result.getBuckets()) {
                std::cout << "bucket: name:" << bucket.name
                          << ", region:" << bucket.region
                          << ", storageClass:" << bucket.storageClass
                          << std::endl;
            }
        }));

    // Wait for the asynchronous operation to complete.
    std::this_thread::sleep_for(std::chrono::seconds(5));

    return 0;
}

The output lists all buckets in your account across all regions.

Client configuration

Supported client parameters

Parameter

Description

region

(Required) The region to send requests to.

credentialsProvider

(Required) The provider for access credentials.

endpoint

The service endpoint.

httpTransport

Specifies the HTTP client. Default: cURL.

retryMaxAttempts

The maximum number of retries for an HTTP request. Default: 3.

retryer

The retry handler for HTTP requests. Default: StandardRetryer with a FullJitterBackoff backoff strategy.

connectTimeout

The connection timeout in milliseconds. Default: 5000.

readWriteTimeout

The data transfer timeout in milliseconds. Default: 20000.

insecureSkipVerify

Skips SSL certificate verification. Default: false (verification is enabled).

enabledRedirect

Enables HTTP redirection. Default: false.

signatureVersion

The signature version. Default: v4. This requires the region parameter to be set.

signer

A custom signer implementation. This overrides signatureVersion if set.

disableSsl

Disables HTTPS and uses HTTP. Default: false (HTTPS is used).

usePathStyle

Uses path-style requests. Default: false (virtual-hosted style is used).

useCName

Uses a custom domain. Default: false.

useDualStackEndpoint

Uses a dual-stack endpoint. Default: false.

useAccelerateEndpoint

Uses a transfer acceleration endpoint. Default: false.

useInternalEndpoint

Uses an internal endpoint. Default: false.

additionalHeaders

Additional headers to include in the v4 signature.

userAgent

Additional information to append to the User-Agent header.

disableClockSkewCorrection

Disables automatic clock skew correction. Default: false (correction is enabled).

disableAutoDetectMimeType

Disables automatic Content-Type detection based on the object key. Default: false (detection is enabled).

disableUploadCRC64Check

Disables the CRC64 check for upload requests (PutObject, AppendObject, UploadPart, and Uploader). Default: false (the check is enabled).

disableDownloadCRC64Check

Disables the CRC64 check for download requests (GetObjectToFile and Downloader.DownloadFile). Default: false (the check is enabled).

executor

The thread pool implementation for asynchronous operations in OSSClient, such as asyncCall and asyncCallback. If this parameter is not set, calling asyncCall returns a NoExecutor error.

asyncHttpTransport

The asynchronous HTTP transport layer for OSSAsyncClient. Default: CurlMultiTransport.

scheduledExecutor

The internal task scheduler for OSSAsyncClient. The SDK uses its built-in implementation by default.

Use a custom domain

A custom domain enables browser-based file preview and CDN-accelerated delivery.

Before you run the sample code, replace <region-id> with an actual region ID from the region and endpoint list, such as ap-southeast-1.
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.endpoint = "https://your-custom-domain.com";
    conf.useCName = true;
    conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();

    oss::OSSClient client(conf);

    // Perform operations using the custom domain.
    auto outcome = client.putObject(
        oss::models::PutObjectRequest()
            .setBucket("your-bucket")
            .setKey("your-key")
            .setBody(oss::RequestBody::fromString("Hello, OSS!")));

    if (!outcome.has_value()) {
        auto& err = outcome.error();
        std::cerr << "Error: " << err.getMessage() << std::endl;
        return 1;
    }

    std::cout << "Upload successful" << std::endl;
    return 0;
}

Timeout control

Use connectTimeout and readWriteTimeout to configure the connection and read/write timeouts in milliseconds.

auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Set the connection timeout to 10 seconds.
conf.connectTimeout = 10000;
// Set the read/write timeout to 30 seconds.
conf.readWriteTimeout = 30000;

oss::OSSClient client(conf);

Retry policy

The built-in StandardRetryer uses a FullJitterBackoff strategy with a maximum of 3 retries by default. Use retryMaxAttempts to adjust.

auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Set the maximum number of retries to 5.
conf.retryMaxAttempts = 5;

oss::OSSClient client(conf);

Custom retry strategy example: CustomRetryStrategy.cpp.

HTTP/HTTPS protocol

The HTTPS protocol is used by default. To use the HTTP protocol, set disableSsl to true.

auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Use the HTTP protocol.
conf.disableSsl = true;

oss::OSSClient client(conf);

Use an internal endpoint

When deployed on ECS, use an internal endpoint to avoid public network traffic costs.

auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Use an internal endpoint.
conf.useInternalEndpoint = true;

oss::OSSClient client(conf);

Use a transfer acceleration endpoint

Use a transfer acceleration endpoint for long-distance data transfers.

auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
// Use a transfer acceleration endpoint.
conf.useAccelerateEndpoint = true;

oss::OSSClient client(conf);

Use a custom domain (CNAME)

Access OSS by using a custom domain (CNAME).

auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region-id>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
conf.endpoint = "https://your-custom-domain.com";
conf.useCName = true;

oss::OSSClient client(conf);

Customize the HTTP transport

The SDK uses cURL by default. Replace it via httpTransport. WinHTTP is also supported on Windows.

Custom transport examples: CurlCustomConfig.cpp and WinHttpCustomConfig.cpp.

Configure access credentials

The SDK supports the following credential methods:

How to choose a credential method

Credential method

Use cases

Requires existing credentials

Credential type

Credential validity

Rotation or refresh

Use a RAM user's access key

For applications that run in a secure, stable environment that is not exposed to external attacks and require long-term access to cloud services without frequent credential rotation.

Yes

Access key

Long-term

Manual rotation

Use an STS temporary credential

For applications that run in an untrusted environment and require control over access validity and permissions.

Yes

STS token

Temporary

Manual refresh

Use RAMRoleARN

For applications that require delegated access to cloud services, such as accessing resources across different Alibaba Cloud accounts.

Yes

STS token

Temporary

Automatic refresh

Use ECSRAMRole

For applications deployed on Alibaba Cloud ECS instances, ECI instances, or worker nodes in Container Service for Kubernetes (ACK).

No

STS token

Temporary

Automatic refresh

Use OIDCRoleARN

For untrusted applications deployed on worker nodes in Container Service for Kubernetes (ACK).

No

STS token

Temporary

Automatic refresh

Use anonymous access

For accessing public-read OSS resources.

No

None

-

-

Use a custom credential

If none of the preceding methods meet your requirements, you can implement a custom credential provider.

Custom

Custom

Custom

Custom

RAM user access key

Use a RAM user's access key for applications in a secure, non-internet-exposed environment.

Environment variables (Recommended)

Obtain credentials from the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

  1. Set the environment variables by using the access key of a RAM user.

    Linux

    1. From the command line, run the following commands to append the environment variable settings to the ~/.bashrc file.

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Run the following command to apply the changes.

      source ~/.bashrc
    3. Run the following commands to verify that the environment variables are set.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. In the terminal, run the following command to check your default shell type.

      echo $SHELL
    2. Follow the steps based on your default shell type.

      Zsh

      1. Run the following commands to append the environment variable settings to the ~/.zshrc file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Run the following command to apply the changes.

        source ~/.zshrc
      3. Run the following commands to verify that the environment variables are set.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Run the following commands to append the environment variable settings to the ~/.bash_profile file.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
      2. Run the following command to apply the changes.

        source ~/.bash_profile
      3. Run the following commands to verify that the environment variables are set.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. In CMD, run the following commands.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Reopen CMD and run the following commands to verify that the environment variables are set.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. In PowerShell, run the following commands.

      [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_ID', 'YOUR_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User)
      [System.Environment]::SetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', 'YOUR_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User)
    2. Reopen PowerShell and run the following commands to verify that the environment variables are set.

      [System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_ID', [System.EnvironmentVariableTarget]::User)
      [System.Environment]::GetEnvironmentVariable('OSS_ACCESS_KEY_SECRET', [System.EnvironmentVariableTarget]::User)
  2. After modifying system environment variables, restart your IDE and terminal for changes to take effect.

  3. Use the environment variables to pass the credentials.

    Before you run the sample code, replace <region-id> with an actual region ID, such as cn-hangzhou.
    #include "alibabacloud/oss2/ClientConfiguration.h"
    #include "alibabacloud/oss2/OSSClient.h"
    #include "alibabacloud/oss2/credentials/CredentialsProvider.h"
    
    namespace oss = alibabacloud::oss2;
    
    int main() {
        auto conf = oss::ClientConfiguration::loadDefault();
        conf.region = "<region-id>";
        conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
    
        oss::OSSClient client(conf);
        // Use the client to perform operations.
        return 0;
    }

Explicitly in code

You can explicitly provide the access key ID and access key secret by using StaticCredentialsProvider.

Warning

This method exposes your access key in the code and is recommended for testing purposes only. For production environments, use a more secure method, such as environment variables.

#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = std::make_shared<oss::StaticCredentialsProvider>(
        "YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET");

    oss::OSSClient client(conf);
    // Use the client to perform operations.
    return 0;
}

STS temporary credential

STS temporary credentials consist of an access key ID, access key secret, and security token. You must manually manage and refresh the token.

Note
  • To obtain an STS temporary credential using an SDK, see Use STS temporary credentials to access OSS.

  • When you generate an STS token, you must specify an expiration time. The token automatically becomes invalid after it expires.

  • Note that access key IDs obtained from STS start with the prefix STS, for example, STS.L4aBSCSJVMuKg5U1****.

Environment variables (Recommended)

Obtain temporary credentials by using the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables.

  1. Set the environment variables by using the temporary credentials.

    macOS, Linux, or Unix

    export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>

    Windows

    set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID>
    set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET>
    set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
  2. Use the environment variables to pass the credentials. The SDK's EnvironmentVariableCredentialsProvider automatically reads these three environment variables.

    Before you run the sample code, replace <region-id> with an actual region ID, such as cn-hangzhou.
    #include "alibabacloud/oss2/ClientConfiguration.h"
    #include "alibabacloud/oss2/OSSClient.h"
    #include "alibabacloud/oss2/credentials/CredentialsProvider.h"
    
    namespace oss = alibabacloud::oss2;
    
    int main() {
        auto conf = oss::ClientConfiguration::loadDefault();
        conf.region = "<region-id>";
        // Automatically reads OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN.
        conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
    
        oss::OSSClient client(conf);
        // Use the client to perform operations.
        return 0;
    }

Explicitly in code

You can explicitly provide the temporary access key ID, access key secret, and security token by using StaticCredentialsProvider.

Warning

Testing only. Do not embed credentials in production code. Use environment variables or an auto-refreshing SDK method instead.

#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = std::make_shared<oss::StaticCredentialsProvider>(
        "STS_ACCESS_KEY_ID", "STS_ACCESS_KEY_SECRET", "STS_SECURITY_TOKEN");

    oss::OSSClient client(conf);
    // Use the client to perform operations.
    return 0;
}

RAMRoleARN, ECSRAMRole, or OIDCRoleARN

For credential methods such as RAMRoleARN, ECSRAMRole, and OIDCRoleARN, we recommend using the alibabacloud-credentials-cpp library with CredentialsProviderFunc.

  1. Install the dependency.

    vcpkg install alibabacloud-credentials-cpp
  2. Add the dependency in your CMakeLists.txt file.

    find_package(alibabacloud_credentials REQUIRED)
  3. Integrate the library by using CredentialsProviderFunc.

    RAMRoleARN

    #include "alibabacloud/oss2/ClientConfiguration.h"
    #include "alibabacloud/oss2/OSSClient.h"
    #include "alibabacloud/oss2/credentials/CredentialsProvider.h"
    #include <darabonba/core/Client.hpp>
    #include <alibabacloud/credential.hpp>
    
    namespace oss = alibabacloud::oss2;
    
    int main() {
        auto credConfig = std::make_shared<Alibabacloud_Credential::Config>();
        // The credential type must be ram_role_arn.
        credConfig->type = std::make_shared<std::string>("ram_role_arn");
        // The access key ID of the RAM user. To avoid hardcoding, we recommend injecting this value through the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable.
        credConfig->accessKeyId = std::make_shared<std::string>("YOUR_ACCESS_KEY_ID");
        // The access key secret of the RAM user. To avoid hardcoding, we recommend injecting this value through the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable.
        credConfig->accessKeySecret = std::make_shared<std::string>("YOUR_ACCESS_KEY_SECRET");
        // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole
        // You can also set this value by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        credConfig->roleArn = std::make_shared<std::string>("YOUR_ROLE_ARN");
        // The role session name, used for auditing purposes. You can also set this value by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        credConfig->roleSessionName = std::make_shared<std::string>("your-session-name");
        // (Optional) Further restrict permissions with a policy. This parameter is not required.
        // Example: {"Statement":[{"Action":["oss:GetObject"],"Effect":"Allow","Resource":["*"]}],"Version":"1"}
        // credConfig->policy = std::make_shared<std::string>("<Policy>");
        // (Optional) The role session duration in seconds. Default: 3600 (1 hour). This parameter is not required.
        // credConfig->roleSessionExpiration = std::make_shared<long>(3600);
    
        auto credClient = std::make_shared<Alibabacloud_Credential::Client>(credConfig);
    
        auto conf = oss::ClientConfiguration::loadDefault();
        conf.region = "<region-id>";
        conf.credentialsProvider = std::make_shared<oss::CredentialsProviderFunc>(
            [credClient]() -> oss::Credentials {
                auto cred = credClient->getCredential();
                auto ak = cred.getAccessKeyId();
                auto sk = cred.getAccessKeySecret();
                if (ak.empty() || sk.empty()) {
                    return oss::Credentials::withRetryableError(
                        "failed to get credentials from alibabacloud-credentials-cpp");
                }
                auto token = cred.getSecurityToken();
                return oss::Credentials(std::move(ak), std::move(sk), std::move(token));
            });
    
        oss::OSSClient client(conf);
        // Use the client to perform operations.
        return 0;
    }

    ECSRAMRole

    #include "alibabacloud/oss2/ClientConfiguration.h"
    #include "alibabacloud/oss2/OSSClient.h"
    #include "alibabacloud/oss2/credentials/CredentialsProvider.h"
    #include <darabonba/core/Client.hpp>
    #include <alibabacloud/credential.hpp>
    
    namespace oss = alibabacloud::oss2;
    
    int main() {
        auto credConfig = std::make_shared<Alibabacloud_Credential::Config>();
        // The credential type must be ecs_ram_role.
        credConfig->type = std::make_shared<std::string>("ecs_ram_role");
        // The name of the RAM role granted to the ECS instance. This parameter is optional.
        // If you do not set it, the SDK automatically retrieves it from the metadata service.
        // We strongly recommend setting this parameter explicitly to reduce requests to the metadata service.
        credConfig->roleName = std::make_shared<std::string>("YOUR_ECS_ROLE_NAME");
    
        auto credClient = std::make_shared<Alibabacloud_Credential::Client>(credConfig);
    
        auto conf = oss::ClientConfiguration::loadDefault();
        conf.region = "<region-id>";
        conf.credentialsProvider = std::make_shared<oss::CredentialsProviderFunc>(
            [credClient]() -> oss::Credentials {
                auto cred = credClient->getCredential();
                auto ak = cred.getAccessKeyId();
                auto sk = cred.getAccessKeySecret();
                if (ak.empty() || sk.empty()) {
                    return oss::Credentials::withRetryableError(
                        "failed to get credentials from alibabacloud-credentials-cpp");
                }
                auto token = cred.getSecurityToken();
                return oss::Credentials(std::move(ak), std::move(sk), std::move(token));
            });
    
        oss::OSSClient client(conf);
        // Use the client to perform operations.
        return 0;
    }

    OIDCRoleARN

    #include "alibabacloud/oss2/ClientConfiguration.h"
    #include "alibabacloud/oss2/OSSClient.h"
    #include "alibabacloud/oss2/credentials/CredentialsProvider.h"
    #include <darabonba/core/Client.hpp>
    #include <alibabacloud/credential.hpp>
    
    namespace oss = alibabacloud::oss2;
    
    int main() {
        auto credConfig = std::make_shared<Alibabacloud_Credential::Config>();
        // The credential type must be oidc_role_arn.
        credConfig->type = std::make_shared<std::string>("oidc_role_arn");
        // The ARN of the RAM role to assume. You can also set this value by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
        credConfig->roleArn = std::make_shared<std::string>("YOUR_ROLE_ARN");
        // The ARN of the OIDC identity provider. You can also set this value by using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        credConfig->oidcProviderArn = std::make_shared<std::string>("YOUR_OIDC_PROVIDER_ARN");
        // The path to the OIDC token file, which is automatically mounted into the pod by RRSA. You can also set this value by using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        credConfig->oidcTokenFilePath = std::make_shared<std::string>("/var/run/secrets/tokens/oidc-token");
        // The role session name, used for auditing purposes. You can also set this value by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        credConfig->roleSessionName = std::make_shared<std::string>("your-session-name");
        // (Optional) Further restrict permissions with a policy. This parameter is not required.
        // credConfig->policy = std::make_shared<std::string>("<Policy>");
    
        auto credClient = std::make_shared<Alibabacloud_Credential::Client>(credConfig);
    
        auto conf = oss::ClientConfiguration::loadDefault();
        conf.region = "<region-id>";
        conf.credentialsProvider = std::make_shared<oss::CredentialsProviderFunc>(
            [credClient]() -> oss::Credentials {
                auto cred = credClient->getCredential();
                auto ak = cred.getAccessKeyId();
                auto sk = cred.getAccessKeySecret();
                if (ak.empty() || sk.empty()) {
                    return oss::Credentials::withRetryableError(
                        "failed to get credentials from alibabacloud-credentials-cpp");
                }
                auto token = cred.getSecurityToken();
                return oss::Credentials(std::move(ak), std::move(sk), std::move(token));
            });
    
        oss::OSSClient client(conf);
        // Use the client to perform operations.
        return 0;
    }

    More credential examples: credentials examples.

Anonymous access

Access public-read buckets and objects without credentials.

#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

namespace oss = alibabacloud::oss2;

int main() {
    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = std::make_shared<oss::AnonymousCredentialsProvider>();

    oss::OSSClient client(conf);
    // Use the client to perform operations.
    return 0;
}

Custom credential provider

Implement custom credential retrieval logic with CredentialsProviderFunc.

#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"

#include <cstdlib>

namespace oss = alibabacloud::oss2;

// Example: Load credentials from custom environment variables or a configuration file.
static oss::Credentials loadCredentialsFromCustomSource() {
    // In a real-world application, you can retrieve credentials from various sources:
    //   - A configuration file (such as ~/.ossrc)
    //   - A key management service (such as HashiCorp Vault or KMS)
    //   - A metadata service
    //   - A database
    const char* ak = std::getenv("MY_APP_ACCESS_KEY_ID");
    const char* sk = std::getenv("MY_APP_ACCESS_KEY_SECRET");
    const char* token = std::getenv("MY_APP_SESSION_TOKEN");

    if (!ak || !sk) {
        // The error message propagates to OperationError::getMessage().
        return oss::Credentials::withError(
            "MY_APP_ACCESS_KEY_ID and MY_APP_ACCESS_KEY_SECRET must be set");
        // For transient failures, such as network timeouts, use withRetryableError.
        // The SDK automatically retries credential retrieval.
        // return oss::Credentials::withRetryableError("...");
    }

    return oss::Credentials(ak, sk, token ? token : "");
}

int main() {
    // The custom credential provider function is called every time credentials are required,
    // allowing you to implement rotation, refresh, or caching logic.
    auto provider = std::make_shared<oss::CredentialsProviderFunc>(
        loadCredentialsFromCustomSource);

    auto conf = oss::ClientConfiguration::loadDefault();
    conf.region = "<region-id>";
    conf.credentialsProvider = provider;

    oss::OSSClient client(conf);
    // Use the client to perform operations.
    return 0;
}

Calling API operations

API operations follow a consistent naming convention and calling pattern.

API naming convention

Method names use camelCase style. Each operation takes an <OperationName>Request parameter and returns an <OperationName>Outcome (Outcome<Result, Error>).

OSSClient (synchronous):

OutcomeType operationName(const models::OperationNameRequest& request, const OperationOptions* options = nullptr)

OSSAsyncClient (native asynchronous):

void operationNameAsync(const models::OperationNameRequest& request, const OperationNameAsyncCallback& callback, const OperationOptions* options = nullptr)

Calling modes

Calling mode

OSSClient

OSSAsyncClient

synchronous

operationName(request)

-

future-based asynchronous

asyncCall(request) (requires conf.executor to be configured)

asyncCall(request)

callback-based asynchronous

asyncCallback(request, cb) (requires conf.executor to be configured)

operationNameAsync(request, cb)

Canceling a request

To cancel long-running operations with a CancellationToken, pass a cancellationToken in OperationOptions. The OSS C++ SDK V2 provides two cancellation modes:

Cancel immediately

Call CancellationTokenSource::cancel() from another thread to interrupt an in-progress request.

// Cancel the request from another thread.
auto cts = oss::CancellationTokenSource::create();

oss::OperationOptions opts;
opts.cancellationToken = cts->getToken();

// Start the request in another thread.
auto future = std::async([&]() {
    return client.getObject(request, &opts);
});

// Cancel from the current thread.
cts->cancel();

Cancel by deadline

Call cancelAfter() to set a timeout. The SDK automatically cancels the request when the timeout expires.

// Set a 30-second timeout for automatic cancellation.
auto cts = oss::CancellationTokenSource::create();
cts->cancelAfter(std::chrono::seconds(30));

oss::OperationOptions opts;
opts.cancellationToken = cts->getToken();

auto outcome = client.getObject(request, &opts);

Error handling

The OSS C++ SDK V2 uses Outcome<Result, Error>, which is compatible with std::expected. Call has_value() to check for success. If successful, retrieve the result with value() or by dereferencing the outcome object (*outcome). Otherwise, retrieve the error object with error().

auto outcome = client.putObject(request);

if (!outcome.has_value()) {
    auto& err = outcome.error();
    std::cerr << "Error code: " << err.getCode() << std::endl;
    std::cerr << "Error message: " << err.getMessage() << std::endl;
    std::cerr << "EC: " << err.getEC() << std::endl;
    std::cerr << "Request ID: " << err.getRequestId() << std::endl;
    std::cerr << "Request target: " << err.getRequestTarget() << std::endl;
}

When you build with the -DUSE_STD_EXPECTED=ON flag (C++23), Outcome becomes a type alias for std::expected, which supports monadic operations such as .and_then(), .transform(), and .or_else().

Sample code

The following table lists the available sample code.

Category

Description

Synchronous version

Asynchronous version

Buckets

Create a bucket

PutBucket.cpp

PutBucket.cpp

List buckets

ListBuckets.cpp

ListBuckets.cpp

Delete a bucket

DeleteBucket.cpp

DeleteBucket.cpp

Get bucket information

GetBucketInfo.cpp

GetBucketInfo.cpp

Get bucket location

GetBucketLocation.cpp

GetBucketLocation.cpp

Object upload

Simple upload

PutObject.cpp

PutObject.cpp

Append upload

AppendObject.cpp

AppendObject.cpp

Multipart upload

UploadPart.cpp

UploadPart.cpp

Multipart copy

UploadPartCopy.cpp

UploadPartCopy.cpp

Object download

Simple download

GetObject.cpp

GetObject.cpp

Copy an object

CopyObject.cpp

CopyObject.cpp

Object management

List objects

ListObjects.cpp

ListObjects.cpp

List objects V2

ListObjectsV2.cpp

ListObjectsV2.cpp

Delete an object

DeleteObject.cpp

DeleteObject.cpp

Delete multiple objects

DeleteMultipleObjects.cpp

DeleteMultipleObjects.cpp

Get object metadata

HeadObject.cpp

HeadObject.cpp

Get simplified object metadata

GetObjectMeta.cpp

GetObjectMeta.cpp

Archived objects

Restore an object

RestoreObject.cpp

RestoreObject.cpp

Delete a restored object

CleanRestoredObject.cpp

CleanRestoredObject.cpp

Symbolic links

Create a symbolic link

PutSymlink.cpp

PutSymlink.cpp

Get a symbolic link

GetSymlink.cpp

GetSymlink.cpp

Object tagging

Set object tagging

PutObjectTagging.cpp

PutObjectTagging.cpp

Get object tagging

GetObjectTagging.cpp

GetObjectTagging.cpp

Delete object tagging

DeleteObjectTagging.cpp

DeleteObjectTagging.cpp

Access control

Set bucket ACL

PutBucketAcl.cpp

PutBucketAcl.cpp

Get bucket ACL

GetBucketAcl.cpp

GetBucketAcl.cpp

Set object ACL

PutObjectAcl.cpp

PutObjectAcl.cpp

Versioning

Set bucket versioning

PutBucketVersioning.cpp

PutBucketVersioning.cpp

Get bucket versioning status

GetBucketVersioning.cpp

GetBucketVersioning.cpp

List object versions

ListObjectVersions.cpp

ListObjectVersions.cpp

Hotlink protection

Set hotlink protection

PutBucketReferer.cpp

PutBucketReferer.cpp

Get hotlink protection configuration

GetBucketReferer.cpp

GetBucketReferer.cpp

System functions

Query endpoint information

DescribeRegions.cpp

DescribeRegions.cpp

Presigned URL

Generate a presigned URL for download

PresignGetObject.cpp

-

Generate a presigned URL for upload

PresignPutObject.cpp

-

Generate a presigned URL for a HEAD request

PresignHeadObject.cpp

-

Generate a presigned URL for multipart upload

PresignUploadPart.cpp

-

Generic API

Using invokeOperation

InvokeOperation.cpp

-

Paginator

List all buckets

ListBucketsPaginator.cpp

-

List all objects (recommended)

ListObjectsV2Paginator.cpp

-

List all object versions

ListObjectVersionsPaginator.cpp

-

List all uploaded parts

ListPartsPaginator.cpp

-

List all multipart uploads

ListMultipartUploadsPaginator.cpp

-

List all objects (legacy, not recommended)

ListObjectsPaginator.cpp

-

Scenario examples

SinkFactory series (zero-copy download, resumable upload, and CRC check)

samples/scenario/sink-factory

-

Asynchronous operations with future/callback

samples/scenario/sync-client-async

-

More scenario examples

samples/scenario

-