Todos los productos
Search
Centro de documentos

Object Storage Service:Gestión de permisos de acceso de archivos (SDK de C)

Última actualización: Sep 22, 2026

Además de las listas de control de acceso (ACL) de bucket, OSS ofrece ACL de objeto. Establezca una ACL cuando cargue un objeto o modifique la ACL de un objeto existente en cualquier momento.

Notas

  • En este tema se usa el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región que OSS, use un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Initialization (C SDK).

  • Para configurar la ACL de un objeto, debe contar con el permiso oss:PutObjectAcl. Para consultar las ACL de los objetos, necesita el permiso oss:GetObjectAcl. Para obtener más información, consulte Grant a custom policy.

Tipos de ACL

Los objetos admiten a continuación cuatro tipos de ACL:

Nota

Las ACL de objeto tienen mayor prioridad que las ACL de bucket. Por ejemplo, si un objeto se configura como public-read, cualquier persona, incluidos los usuarios anónimos, puede leerlo aunque el bucket que lo contiene sea privado.

Tipo de permiso

Descripción

Valor del permiso

Heredar del bucket (predeterminado)

Si un objeto no tiene una ACL, hereda la ACL de su bucket.

OSS_ACL_DEFAULT

Privado

Solo el propietario del objeto puede leerlo y escribirlo. Los demás usuarios no pueden acceder al objeto.

OSS_ACL_PRIVATE

Lectura pública

Solo el propietario del objeto puede escribir en él. Cualquier persona, incluidos los usuarios anónimos, puede leer el objeto.

Aviso

Cualquier usuario de Internet puede acceder al objeto. Esto podría provocar fugas de datos y un aumento en los costos. Use este permiso con precaución.

OSS_ACL_PUBLIC_READ

Lectura y escritura públicas

Cualquier persona, incluidos los usuarios anónimos, puede leer y escribir el objeto.

Aviso

Cualquier usuario de Internet puede acceder a este objeto y escribir datos en él. Esta situación genera fugas de datos e incrementa los costos. Además, si usuarios malintencionados escriben información ilegal en el objeto, sus derechos legales podrían verse vulnerados. No configure permisos de lectura y escritura públicas a menos que sea absolutamente necesario.

OSS_ACL_PUBLIC_READ_WRITE

Código de ejemplo

A continuación se muestra un código de ejemplo que indica cómo establecer y recuperar la ACL de un objeto específico:

#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. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize an 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 configured. */
    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"));
    // The following two parameters also need to be configured.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether a CNAME is used. 0 indicates that no CNAME is 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 entrance 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) is used for memory management and is equivalent to apr_pool_t. The 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 new memory pool does not inherit from another memory pool. */
    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 to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    oss_acl_e oss_acl = OSS_ACL_PRIVATE;
    /* Set the object ACL. */
    resp_status = oss_put_object_acl(oss_client_options, &bucket, &object, oss_acl, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put object acl success!\n"); 
    } else {
        printf("put object acl failed!\n"); 
    }
    /* Get the object ACL. */
    aos_string_t oss_acl_string;
    resp_status = oss_get_object_acl(oss_client_options, &bucket, &object, &oss_acl_string, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("get object acl success!\n");
        printf("acl: %s \n", oss_acl_string.data);
    } else {
        printf("get object acl failed!\n");
    }
    /* Release the memory pool. This releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

Referencias

  • Para obtener más información sobre la operación de API usada para establecer los permisos de acceso de un objeto, consulte PutObjectACL.

  • Para obtener más información sobre la operación de API usada para recuperar los permisos de acceso de un objeto, consulte GetObjectACL.