Tous les produits
Search
Centre de documentation

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

Dernière mise à jour :Aug 08, 2026

Cette rubrique explique comment utiliser des identifiants d'accès temporaires fournis par Alibaba Cloud Security Token Service (STS) 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 l'URL présignée. 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 d'accès temporaires STS est de 1200 secondes et celle de l'URL présignée de 3 600 secondes, vous ne pourrez pas utiliser l'URL présignée pour télécharger des fichiers au-delà de 1200 secondes, car les identifiants d'accès temporaires STS auront expiré.

Notes

  • Cette rubrique utilise 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, reportez-vous à 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, telles que l'utilisation d'un domaine personnalisé ou l'authentification via des identifiants issus de Security Token Service (STS), consultez Initialisation (SDK C).

Utiliser STS pour autoriser un accès temporaire

OSS prend en charge l'autorisation d'accès temporaire via Alibaba Cloud Security Token Service (STS). 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 de permissions personnalisées à des applications tierces ou à des sous-utilisateurs (utilisateurs dont vous gérez les identités). Pour plus d'informations sur STS, consultez Présentation de STS.

STS offre les avantages suivants :

  • Vous n'avez pas besoin d'exposer votre paire 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 permissions d'accès ainsi que la durée de validité de ce jeton.

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

Pour accéder à OSS en utilisant des 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 AccessKey temporaire (un ID AccessKey et un secret AccessKey) ainsi qu'un jeton de sécurité (SecurityToken). La durée de validité des identifiants d'accès temporaires est exprimée en secondes. La valeur minimale est de 900. La valeur maximale correspond à la durée maximale de session définie pour le rôle RAM actuel. Pour plus d'informations, consultez Définir la durée maximale de session pour 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. De ce fait, il n'est pas nécessaire d'accorder des permissions 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 pertinentes 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 présignée dispose des permissions correspondantes.

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

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

  • 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 ci-dessous peut contenir un signe plus (+). Dans ce cas, remplacez le signe plus (+) présent dans l'URL par %2B. Sinon, 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

    Vous pouvez vous référer à 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

    Vous pouvez vous référer à 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).