Tous les produits
Search
Centre de documentation

Object Storage Service:Autoriser l'accès (SDK C)

Dernière mise à jour :Sep 22, 2026

Cette rubrique explique comment utiliser des identifiants d'accès temporaires fournis par le service Security Token Service (STS) d'Alibaba Cloud ou une URL pré-signée pour accéder temporairement aux ressources Object Storage Service (OSS).

Important

Vous devez spécifier une durée de validité pour les identifiants d'accès temporaires STS et pour les URL pré-signées. Si vous utilisez des identifiants d'accès temporaires pour générer une URL pré-signée destinée à des opérations telles que le téléchargement ou la récupération de fichiers, c'est la durée de validité la plus courte qui s'applique. Par exemple, si la validité de vos identifiants STS est de 1 200 secondes et celle de l'URL pré-signée de 3 600 secondes, vous ne pourrez pas utiliser l'URL pour télécharger des fichiers au-delà de 1 200 secondes, car les identifiants STS auront expiré.

Notes

  • Dans cette rubrique, nous utilisons le point de terminaison public de la région Chine (Hangzhou). Si vous souhaitez accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un point de terminaison interne. Pour plus d'informations sur les régions et les points de terminaison OSS, consultez Régions et points de terminaison.

  • Cette rubrique illustre la création d'une instance OSSClient avec un point de terminaison OSS. Pour d'autres configurations, comme l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants du service Security Token Service (STS), reportez-vous à Initialisation (SDK C).

Utiliser STS pour autoriser un accès temporaire

OSS prend en charge l'autorisation d'accès temporaire via le service Security Token Service (STS) d'Alibaba Cloud. STS est un service web qui fournit des jetons d'accès temporaires aux utilisateurs du cloud computing. Avec STS, vous pouvez émettre des identifiants d'accès dotés d'une durée de validité et d'autorisations personnalisées à des applications tierces ou à des sous-utilisateurs (utilisateurs dont vous gérez les identités). Pour en savoir plus sur STS, consultez Présentation de STS.

STS offre les avantages suivants :

  • Vous n'avez pas besoin d'exposer votre paire de clés AccessKey à long terme à des applications tierces. Vous pouvez plutôt générer un jeton d'accès et le fournir à l'application. Vous avez la possibilité de personnaliser les autorisations d'accès ainsi que la durée de validité de ce jeton.

  • Aucune gestion de la révocation des autorisations n'est nécessaire. Le jeton d'accès devient automatiquement invalide à son expiration.

Pour accéder à OSS à l'aide d'identifiants d'accès temporaires provenant de STS, procédez comme suit :

  1. Obtenir des identifiants d'accès temporaires

    Les identifiants d'accès temporaires comprennent une paire de clés AccessKey temporaire (un ID de clé AccessKey et un secret AccessKey) ainsi qu'un jeton de sécurité (SecurityToken). La durée de validité de ces identifiants est exprimée en secondes. La valeur minimale est de 900. La valeur maximale correspond à la durée de session maximale définie pour le rôle RAM actuel. Pour plus d'informations, consultez Définir la durée de session maximale d'un rôle RAM.

    Vous pouvez obtenir des identifiants d'accès temporaires de l'une des manières suivantes.

    • Méthode 1

      Appelez l'opération AssumeRole pour obtenir des identifiants d'accès temporaires.

    • Méthode 2

      Utilisez les SDK STS pour obtenir des identifiants d'accès temporaires. Pour plus d'informations, consultez SDK STS.

  2. Utilisez les identifiants STS pour créer une requête signée.

    • Télécharger un fichier

      #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;
      }            
    • Récupérer un fichier

      #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;
      }

Utiliser une URL pré-signée pour autoriser un accès temporaire

Remarques d'utilisation

  • Lorsque vous utilisez un SDK OSS pour générer une URL pré-signée, le SDK applique un algorithme spécifique basé sur les informations de clé stockées sur l'ordinateur local afin de calculer une signature et de l'ajouter à l'URL, garantissant ainsi sa validité et sa sécurité. Les opérations de calcul et de construction de l'URL sont effectuées côté client. Aucune requête réseau vers le serveur n'est nécessaire. Ainsi, vous n'avez pas besoin d'accorder d'autorisations spécifiques à l'appelant lors de la génération de l'URL pré-signée. Toutefois, pour permettre aux utilisateurs tiers d'effectuer les opérations concernées sur les ressources autorisées par l'URL pré-signée, vous devez vous assurer que l'entité appelant les API pour générer l'URL dispose des autorisations correspondantes.

    Par exemple, si une entité souhaite télécharger un objet via une URL pré-signée, vous devez lui accorder l'autorisation oss:PutObject. Si une entité souhaite récupérer ou prévisualiser un objet via une URL pré-signée, vous devez lui accorder l'autorisation oss:GetObject.

  • Vous pouvez générer une URL pré-signée et la communiquer à un visiteur pour un accès temporaire. Lors de la génération, vous avez la possibilité de définir la durée de validité de l'URL afin de limiter la période pendant laquelle le visiteur peut accéder aux données spécifiées.

  • Pour générer une URL pré-signée permettant d'accéder aux ressources via HTTPS, configurez le protocole du point de terminaison sur HTTPS.

  • L'URL pré-signée générée à l'aide de l'exemple de code suivant peut contenir un signe plus (+). Dans ce cas, remplacez le signe plus (+) présent dans l'URL par %2B. À défaut, l'URL pré-signée risque de ne pas permettre l'accès à l'objet comme prévu.

Générer une URL pré-signée et l'utiliser pour télécharger un fichier

  1. Générer une URL pré-signée pour le téléchargement

    #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. Utiliser l'URL pré-signée pour télécharger un fichier

    Reportez-vous à l'exemple de code du SDK Android pour télécharger un fichier à l'aide d'une URL pré-signée. Pour plus d'informations, consultez Autoriser l'accès (SDK Android).

Générer une URL pré-signée et l'utiliser pour récupérer un fichier

  1. Générer une URL pré-signée pour la récupération

    #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. Utiliser l'URL pré-signée pour récupérer un fichier

    Reportez-vous à l'exemple de code du SDK Android pour récupérer un fichier à l'aide d'une URL pré-signée. Pour plus d'informations, consultez Autoriser l'accès (SDK Android).