Todos os produtos
Search
Central de documentação

Object Storage Service:Authorize access (C SDK)

Última atualização: Sep 22, 2026

Este tópico descreve como usar credenciais de acesso temporárias do Alibaba Cloud Security Token Service (STS) ou uma URL pré-assinada para acessar temporariamente recursos do Object Storage Service (OSS).

Importante

Especifique um período de validade para as credenciais de acesso temporárias do STS e para a URL pré-assinada. Se você usar credenciais temporárias para gerar uma URL pré-assinada para operações como upload ou download de arquivos, o período de validade mais curto será o aplicado. Por exemplo, suponha que a validade das suas credenciais do STS seja de 1200 segundos e a da URL pré-assinada seja de 3600 segundos. Nesse caso, você não poderá usar a URL pré-assinada para fazer upload de arquivos após 1200 segundos, pois as credenciais do STS já terão expirado.

Observações

  • Neste tópico, o endpoint público da região China (Hangzhou) é utilizado. Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região do OSS, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como o uso de um domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Initialization (C SDK).

Usar o STS para autorizar acesso temporário

O OSS oferece suporte à autorização de acesso temporário por meio do Alibaba Cloud Security Token Service (STS). O STS é um serviço web que fornece tokens de acesso temporários para usuários de computação em nuvem. Com o STS, você pode emitir uma credencial de acesso com período de validade e permissões personalizados para aplicações de terceiros ou subusuários (usuários cujas identidades você gerencia). Para mais informações sobre o STS, consulte What is STS.

O STS oferece os seguintes benefícios:

  • Não é necessário expor seu par de AccessKey de longo prazo para aplicações de terceiros. Em vez disso, gere um token de acesso e forneça-o à aplicação. É possível personalizar as permissões de acesso e o período de validade desse token.

  • Não há necessidade de gerenciar a revogação de permissões. O token de acesso torna-se inválido automaticamente ao expirar.

Para acessar o OSS usando credenciais de acesso temporárias do STS, execute as seguintes etapas:

  1. Obtenha credenciais de acesso temporárias

    As credenciais de acesso temporárias incluem um par de AccessKey temporário (um AccessKeyID e um AccessKeySecret) e um token de segurança (SecurityToken). O período de validade das credenciais de acesso temporárias é especificado em segundos. O valor mínimo é 900. O valor máximo é a duração máxima da sessão especificada para a função do RAM atual. Para mais informações, consulte Set the maximum session duration for a RAM role.

    Obtenha as credenciais de acesso temporárias de uma das seguintes maneiras:

    • Método 1

      Chame a operação AssumeRole para obter as credenciais de acesso temporárias.

    • Método 2

      Use os SDKs do STS para obter as credenciais de acesso temporárias. Para mais informações, consulte STS SDKs.

  2. Use as credenciais do STS para criar uma solicitação assinada:

    • Faça upload de um arquivo

      #include "oss_api.h"
      #include "aos_http_io.h"
      /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
      const char *endpoint = "yourEndpoint";
      /* Before you run this sample code, make sure that you have set the YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET environment variables based on the temporary AccessKey pair obtained from STS. */  
      const char *access_key_id = getenv("OSS_ACCESS_KEY_ID");
      const char *access_key_secret = getenv("OSS_ACCESS_KEY_SECRET");
      /* The security token (SecurityToken) obtained from STS. */
      const char *sts_token = "yourStsToken";
      /* Specify the bucket name. For example, examplebucket. */
      const char *bucket_name = "examplebucket";
      /* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
      const char *object_name = "exampledir/exampleobject.txt";
      const char *object_content = "More than just cloud.";
      
      void init_options(oss_request_options_t *options)
      {
          options->config = oss_config_create(options->pool);
          /* Initialize the aos_string_t type with a char* string. */
          aos_str_set(&options->config->endpoint, endpoint);
          aos_str_set(&options->config->access_key_id, access_key_id);
          aos_str_set(&options->config->access_key_secret, access_key_secret);
          aos_str_set(&options->config->sts_token, sts_token);
          /* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
          options->config->is_cname = 0;
          /* Set network parameters, such as the timeout period. */
          options->ctl = aos_http_controller_create(options->pool, 0);
      }
      
      int main(int argc, char *argv[])
      {
          /* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
          if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
              exit(1);
          }
      
          /* The memory pool (pool) for memory management, which is equivalent to apr_pool_t. Its implementation code is in the APR library. */
          aos_pool_t *pool;
          /* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
          aos_pool_create(&pool, NULL);
          /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
          oss_request_options_t *oss_client_options;
          /* Allocate memory for options in the memory pool. */
          oss_client_options = oss_request_options_create(pool);
          /* Initialize the client option oss_client_options. */
          init_options(oss_client_options);
      
          /* Initialize parameters. */
          aos_string_t bucket;
          aos_string_t object;
          aos_list_t buffer;
          aos_buf_t *content = NULL;
          aos_table_t *headers = NULL;
          aos_table_t *resp_headers = NULL; 
          aos_status_t *resp_status = NULL; 
          /* Assign the data of the char* type to the bucket. */
          aos_str_set(&bucket, bucket_name);
          aos_str_set(&object, object_name);
      
          aos_list_init(&buffer);
          content = aos_buf_pack(oss_client_options->pool, object_content, strlen(object_content));
          aos_list_add_tail(&content->node, &buffer);
      
          /* Upload the file. */
          resp_status = oss_put_object_from_buffer(oss_client_options, &bucket, &object, &buffer, headers, &resp_headers);
          /* Check whether the file is uploaded. */
          if (aos_status_is_ok(resp_status)) {
              printf("put object from buffer succeeded\n");
          } else {
              printf("put object from buffer failed\n");      
          }    
      
          /* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
          aos_pool_destroy(pool);
      
          /* Release the previously allocated global resources. */
          aos_http_io_deinitialize();
      
          return 0;
      }            
    • Baixe um arquivo

      #include "oss_api.h"
      #include "aos_http_io.h"
      /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
      const char *endpoint = "yourEndpoint";
      /* 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. */  
      const char *access_key_id = getenv("OSS_ACCESS_KEY_ID");
      const char *access_key_secret = getenv("OSS_ACCESS_KEY_SECRET");
      /* The security token (SecurityToken) obtained from STS. */
      const char *sts_token = "yourStsToken";
      /* Specify the bucket name. For example, examplebucket. */
      const char *bucket_name = "examplebucket";
      /* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
      const char *object_name = "exampledir/exampleobject.txt";
      void init_options(oss_request_options_t *options)
      {
          options->config = oss_config_create(options->pool);
          /* Initialize the aos_string_t type with a char* string. */
          aos_str_set(&options->config->endpoint, endpoint);
          aos_str_set(&options->config->access_key_id, access_key_id);
          aos_str_set(&options->config->access_key_secret, access_key_secret);
          aos_str_set(&options->config->sts_token, sts_token);
          /* Specify whether a CNAME is used. A value of 0 indicates that a CNAME is not used. */
          options->config->is_cname = 0;
          /* Used to set network parameters, such as the timeout period. */
          options->ctl = aos_http_controller_create(options->pool, 0);
      }
      int main(int argc, char *argv[])
      {
          /* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
          if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
              exit(1);
          }
          /* The memory pool (pool) for memory management, which is equivalent to apr_pool_t. Its implementation code is in the APR library. */
          aos_pool_t *pool;
          /* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
          aos_pool_create(&pool, NULL);
          /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
          oss_request_options_t *oss_client_options;
          /* Allocate memory for options in the memory pool. */
          oss_client_options = oss_request_options_create(pool);
          /* Initialize the client option oss_client_options. */
          init_options(oss_client_options);
          /* Initialize parameters. */
          aos_string_t bucket;
          aos_string_t object;
          aos_list_t buffer;
          aos_buf_t *content = NULL;
          aos_table_t *params = NULL;
          aos_table_t *headers = NULL;
          aos_table_t *resp_headers = NULL; 
          aos_status_t *resp_status = NULL; 
          char *buf = NULL;
          int64_t len = 0;
          int64_t size = 0;
          int64_t pos = 0;
          aos_str_set(&bucket, bucket_name);
          aos_str_set(&object, object_name);
          aos_list_init(&buffer);
          /* Download the file to the local memory. */
          resp_status = oss_get_object_to_buffer(oss_client_options, &bucket, &object, 
                                       headers, params, &buffer, &resp_headers);
          if (aos_status_is_ok(resp_status)) {
              printf("get object to buffer succeeded\n");
              /* Copy the downloaded content to the buffer. */
              len = aos_buf_list_len(&buffer);
              buf = aos_pcalloc(pool, len + 1);
              buf[len] = '\0';
              aos_list_for_each_entry(aos_buf_t, content, &buffer, node) {
              size = aos_buf_size(content);
                  memcpy(buf + pos, content->pos, size);
                  pos += size;
              }
          }
          else {
              printf("get object to buffer failed\n");  
          }
          /* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
          aos_pool_destroy(pool);
          /* Release the previously allocated global resources. */
          aos_http_io_deinitialize();
          return 0;
      }

Usar uma URL pré-assinada para autorizar acesso temporário

Observações de uso

  • Ao usar um SDK do OSS para gerar uma URL pré-assinada, o SDK utiliza um algoritmo específico com base nas informações de chave armazenadas no computador local. Ele calcula uma assinatura e a adiciona a uma URL, garantindo sua validade e segurança. As operações para calcular e construir a URL são concluídas no cliente. Portanto, não é necessário enviar solicitações ao servidor pela rede. Dessa forma, você não precisa conceder permissões específicas ao chamador ao gerar a URL pré-assinada. No entanto, para permitir que terceiros realizem operações nos recursos autorizados, certifique-se de que a entidade que chama as operações da API para gerar a URL possua as permissões correspondentes.

    Por exemplo, se uma entidade quiser fazer upload de um objeto usando uma URL pré-assinada, conceda a permissão oss:PutObject a ela. Se uma entidade quiser fazer download ou visualizar um objeto usando uma URL pré-assinada, conceda a permissão oss:GetObject a ela.

  • Gere uma URL pré-assinada e forneça-a a um visitante para acesso temporário. Ao gerar uma URL pré-assinada, especifique o período de validade da URL para limitar o tempo durante o qual o visitante pode acessar dados específicos.

  • Para gerar uma URL pré-assinada usada para acessar recursos via HTTPS, defina o protocolo no endpoint como HTTPS.

  • A URL pré-assinada gerada com o código de exemplo a seguir pode conter um sinal de mais (+). Nesse caso, substitua o sinal de mais (+) na URL por %2B. Caso contrário, a URL pré-assinada poderá não ser usada para acessar o objeto conforme o esperado.

Gere uma URL pré-assinada e use-a para fazer upload de um arquivo

  1. Gere uma URL pré-assinada para upload

    #include "oss_api.h"
    #include "aos_http_io.h"
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    const char *endpoint = "yourEndpoint";
    
    /* Specify the bucket name. For example, examplebucket. */
    const char *bucket_name = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
    const char *object_name = "exampledir/exampleobject.txt";
    /* Specify the full path of the local file. */
    const char *local_filename = "yourLocalFilename";
    void init_options(oss_request_options_t *options)
    {
        options->config = oss_config_create(options->pool);
        /* Initialize the aos_string_t type with a char* string. */
        aos_str_set(&options->config->endpoint, endpoint);
        /* 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. */
        aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
        aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
        /* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
        options->config->is_cname = 0;
        /* Set network parameters, such as the timeout period. */
        options->ctl = aos_http_controller_create(options->pool, 0);
    }
    int main(int argc, char *argv[])
    {
        /* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
        if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
            exit(1);
        }
        /* The memory pool (pool) for memory management, which is equivalent to apr_pool_t. Its implementation code is in the APR library. */
        aos_pool_t *pool;
        /* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
        aos_pool_create(&pool, NULL);
        /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
        oss_request_options_t *oss_client_options;
        /* Allocate memory for options in the memory pool. */
        oss_client_options = oss_request_options_create(pool);
        /* Initialize the client option oss_client_options. */
        init_options(oss_client_options);
        /* Initialize parameters. */
        aos_string_t bucket;
        aos_string_t object;
        aos_string_t file;    
        aos_http_request_t *req;
        apr_time_t now;
        char *url_str;
        aos_string_t url;
        int64_t expire_time; 
        int one_hour = 3600;
        aos_str_set(&bucket, bucket_name);
        aos_str_set(&object, object_name);
        aos_str_set(&file, local_filename);
        expire_time = now / 1000000 + one_hour;    
        req = aos_http_request_create(pool);
        req->method = HTTP_PUT;
        now = apr_time_now(); 
        /* Unit: microseconds. */
        expire_time = now / 1000000 + one_hour;
        /* Generate a presigned URL. */
        url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
        aos_str_set(&url, url_str);
        printf("Temporary upload URL: %s\n", url_str);    
        /* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
        aos_pool_destroy(pool);
        /* Release the previously allocated global resources. */
        aos_http_io_deinitialize();
        return 0;
    }
  2. Use a URL pré-assinada para fazer upload de um arquivo

    Consulte o código de exemplo do SDK para Android para fazer upload de um arquivo usando uma URL pré-assinada. Para mais informações, consulte Authorize access (Android SDK).

Gere uma URL pré-assinada e use-a para baixar um arquivo

  1. Gere uma URL pré-assinada para download

    #include "oss_api.h"
    #include "aos_http_io.h"
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    const char *endpoint = "yourEndpoint";
    /* Specify the bucket name. For example, examplebucket. */
    const char *bucket_name = "examplebucket";
    /* Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/exampleobject.txt. */
    const char *object_name = "exampledir/exampleobject.txt";
    /* Specify the full path of the local file. */
    const char *local_filename = "yourLocalFilename";
    
    void init_options(oss_request_options_t *options)
    {
        options->config = oss_config_create(options->pool);
        /* Initialize the aos_string_t type with a char* string. */
        aos_str_set(&options->config->endpoint, endpoint);
        /* 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. */
        aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
        aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
        /* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
        options->config->is_cname = 0;
        /* Set network parameters, such as the timeout period. */
        options->ctl = aos_http_controller_create(options->pool, 0);
    }
    int main(int argc, char *argv[])
    {
        /* Call the aos_http_io_initialize method at the program entry to initialize global resources, such as the network and memory. */
        if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
            exit(1);
        }
        /* The memory pool (pool) for memory management, which is equivalent to apr_pool_t. Its implementation code is in the APR library. */
        aos_pool_t *pool;
        /* Create a new memory pool. The second parameter is NULL, which indicates that the pool does not inherit from other memory pools. */
        aos_pool_create(&pool, NULL);
        /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
        oss_request_options_t *oss_client_options;
        /* Allocate memory for options in the memory pool. */
        oss_client_options = oss_request_options_create(pool);
        /* Initialize the client option oss_client_options. */
        init_options(oss_client_options);
        /* Initialize parameters. */
        aos_string_t bucket;
        aos_string_t object;
        aos_string_t file;    
        aos_http_request_t *req;
        apr_time_t now;
        char *url_str;
        aos_string_t url;
        int64_t expire_time; 
        int one_hour = 3600;
        aos_str_set(&bucket, bucket_name);
        aos_str_set(&object, object_name);
        aos_str_set(&file, local_filename);
        expire_time = now / 1000000 + one_hour;    
        req = aos_http_request_create(pool);
        req->method = HTTP_GET;
        now = apr_time_now();  
        /* Unit: microseconds. */
        expire_time = now / 1000000 + one_hour;
        /* Generate a presigned URL. */
        url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
        aos_str_set(&url, url_str);
        printf("Temporary download URL: %s\n", url_str);     
        /* Release the memory pool. This is equivalent to releasing the memory allocated for various resources during the request. */
        aos_pool_destroy(pool);
        /* Release the previously allocated global resources. */
        aos_http_io_deinitialize();
        return 0;
    }
  2. Use a URL pré-assinada para baixar um arquivo

    Consulte o código de exemplo do SDK para Android para baixar um arquivo usando uma URL pré-assinada. Para mais informações, consulte Authorize access (Android SDK).