Todos los productos
Search
Centro de documentos

Object Storage Service:OSS Go SDK V1

Última actualización: Sep 03, 2026

Se recomienda utilizar la versión más reciente OSS Go SDK V2 (alibabacloud-oss-go-sdk-v2), que ofrece mejoras arquitectónicas significativas respecto a la V1 (aliyun-oss-go-sdk). La versión V2 simplifica la verificación de identidad, los reintentos de solicitud y el manejo de errores. Además, incorpora interfaces avanzadas como paginadores, administradores de transferencia e interfaces tipo archivo. Para actualizar, consulte Go SDK V1 to V2 Migration Guide.

Integración rápida

Complete los siguientes pasos para integrar OSS Go SDK V1.

image

Preparar el entorno

Descargue e instale el entorno de compilación y ejecución de Go. Para obtener más información, consulte Install Go. Utilice Go 1.13 o una versión posterior.

  • A partir de Go 1.13, el modo de módulos se habilita de forma predeterminada para gestionar las dependencias de paquetes. No es necesario configurar manualmente GOPATH.

  • En Go 1.12 y versiones anteriores, debe establecer la variable de entorno del sistema GOPATH y apuntarla a su directorio de código.

Ejecute el comando go version para consultar la versión de Go instalada.

Instalar el SDK

Seleccione un método de instalación según su entorno de desarrollo. Se recomienda utilizar la versión más reciente del SDK.

go mod (Recommended)

Agregue la siguiente dependencia al archivo go.mod. Este ejemplo utiliza la versión 3.0.2; sustitúyala por la versión que requiera.

require (
    github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
)

From source code

Ejecute el siguiente comando para instalar el SDK:

go get github.com/aliyun/aliyun-oss-go-sdk/oss

El proceso de instalación no muestra mensajes en pantalla. Si se agota el tiempo de espera durante la instalación, ejecute el comando nuevamente.

Configurar credenciales de acceso

Configure las credenciales de acceso con el par de AccessKey de un usuario de RAM.

  1. En la RAM console, cree un usuario de RAM con un Permanent AccessKey Pair. Guarde el par de AccessKey y otorgue al usuario el permiso AliyunOSSFullAccess.

  2. Utilice el par de AccessKey del usuario de RAM para configurar las variables de entorno.

    Linux

    1. Ejecute los siguientes comandos en la interfaz de línea de comandos para agregar la configuración de variables de entorno al archivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Ejecute el siguiente comando para aplicar los cambios.

      source ~/.bashrc
    3. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas correctamente.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Ejecute el siguiente comando en la terminal para consultar el tipo de shell predeterminado.

      echo $SHELL
    2. Realice las siguientes operaciones según el tipo de shell predeterminado.

      Zsh

      1. Ejecute los siguientes comandos para agregar la configuración de variables de entorno al archivo ~/.zshrc.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Ejecute el siguiente comando para aplicar los cambios.

        source ~/.zshrc
      3. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas correctamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Ejecute los siguientes comandos para agregar la configuración de variables de entorno al archivo ~/.bash_profile.

        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. Ejecute el siguiente comando para aplicar los cambios.

        source ~/.bash_profile
      3. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas correctamente.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Ejecute los siguientes comandos en CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas correctamente.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Ejecute los siguientes comandos en PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas correctamente.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)

Inicializar el cliente

El siguiente código de ejemplo inicializa un cliente mediante el endpoint público de la región China (Hangzhou) y lista los buckets de la cuenta actual. Para consultar la lista completa de regiones y endpoints, véase Regions and endpoints.

package main

// Sample code for initializing a client in OSS Go SDK V1

import (
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)

	// List all buckets.
	buckets, err := client.ListBuckets()
	if err != nil {
		fmt.Printf("Failed to list buckets: %v\n", err)
		return
	}

	// Print the bucket list.
	fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))

	for _, bucket := range buckets.Buckets {
		fmt.Printf("%s\n", bucket.Name)
	}
}

Configuración del cliente

Al inicializar un cliente, puede personalizar parámetros como el tipo de endpoint, el tiempo de espera y el tamaño del pool de conexiones para ajustarlos a sus requisitos de red y rendimiento.

Click to view configurable client parameters

Parámetro

Descripción

Método

MaxIdleConns

Número máximo de conexiones inactivas. Valor predeterminado: 100.

oss.MaxConns

MaxIdleConnsPerHost

Número máximo de conexiones inactivas por host. Valor predeterminado: 100.

oss.MaxConns

MaxConnsPerHost

Número máximo de conexiones por host. Valor predeterminado: vacío.

oss.MaxConns

ConnectTimeout

Tiempo de espera de conexión HTTP en segundos. Valor predeterminado: 10. Un valor de 0 indica que no hay límite de tiempo.

oss.Timeout

ReadWriteTimeout

Tiempo de espera de lectura o escritura HTTP en segundos. Valor predeterminado: 20. Un valor de 0 indica que no hay límite de tiempo.

oss.Timeout

IsCname

Indica si se utiliza un nombre de dominio personalizado como endpoint. El valor predeterminado es false.

oss.UseCname

UserAgent

Encabezado User-Agent para solicitudes HTTP. Valor predeterminado: aliyun-sdk-go.

oss.UserAgent

ProxyHost

Indica si se habilitan la dirección y el puerto del host del servidor proxy. Valores válidos:

  • true: habilita la dirección y el puerto del host del servidor proxy.

  • false (predeterminado): deshabilita la dirección y el puerto del host del servidor proxy.

oss.AuthProxy

ProxyUser

Nombre de usuario para la autenticación del servidor proxy.

oss.AuthProxy

ProxyPassword

Contraseña para la autenticación del servidor proxy.

oss.AuthProxy

RedirectEnabled

Indica si se habilita la redirección HTTP. Valores válidos:

  • true (predeterminado): habilita la redirección HTTP.

  • false: deshabilita la redirección HTTP.

oss.RedirectEnabled

InsecureSkipVerify

Indica si se habilita la verificación de certificados SSL. Valores válidos:

  • true (predeterminado): omite la verificación de certificados SSL.

  • false: habilita la verificación de certificados SSL.

oss.InsecureSkipVerify

IsEnableCRC

Indica si se habilita la validación de datos CRC. Valores válidos:

  • true (predeterminado): habilita la validación de datos CRC.

  • false: deshabilita la validación de datos CRC.

oss.EnableCRC

LogLevel

Nivel de registro. Valores válidos:

  • oss.LogOff

  • oss.Debug

  • oss.Error

  • oss.Warn

  • oss.Info

oss.SetLogLevel

Utilizar un endpoint interno

Para acceder a OSS a través de una red interna, especifique un endpoint interno al inicializar el cliente de OSS.

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou-internal.aliyuncs.com", // The internal endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
)

Utilizar un nombre de dominio personalizado

Para acceder a OSS mediante un nombre de dominio personalizado, especifíquelo como endpoint y habilite la opción CNAME con oss.UseCname(true) durante la inicialización del cliente.

Antes de utilizar un nombre de dominio personalizado, asegúrese de haberlo vinculado a un bucket. Para obtener más información, consulte Access OSS through a custom domain name .
// Specify whether to use a custom domain name as the endpoint. The default value is false.
cname := oss.UseCname(true)

// Create an OSS client instance.
client, _ := oss.New(
	"http://kitkat-cloud.cn", // A custom domain name.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	cname,
)

Control de tiempo de espera

Utilice el parámetro oss.Timeout para establecer el tiempo de espera de conexión HTTP y el tiempo de espera de lectura/escritura en segundos.

// Set the HTTP connection timeout period to 20 seconds and the HTTP read or write timeout period to 60 seconds.
time := oss.Timeout(20, 60)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	time,
)

Establecer el tamaño del pool de conexiones

Utilice el parámetro oss.MaxConns para ajustar el tamaño del pool de conexiones.

// Set the maximum number of idle connections (MaxIdleConns) to 10. The default value is 100.
// Set the maximum number of idle connections per host (MaxIdleConnsPerHost) to 20. The default value is 100.
// Set the maximum number of connections per host (MaxConnsPerHost) to 50. The default value is empty.
conn := oss.MaxConns(10, 20, 50)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	conn,
)

Deshabilitar la validación de datos CRC

Establezca oss.EnableCRC(false) para deshabilitar la validación de datos CRC.

Importante

Se recomienda encarecidamente mantener habilitada la validación de datos CRC. Si deshabilita esta función, OSS no podrá garantizar la integridad de los datos durante las cargas y descargas.

// Disable CRC data validation.
crc := oss.EnableCRC(false)

// Create an OSS client instance.
client, _ := oss.New(
	"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
	"",
	"",
	oss.SetCredentialsProvider(&provider),
	oss.AuthVersion(oss.AuthV4),
	oss.Region("cn-hangzhou"),
	crc,
)

Versión de firma

Importante

Las firmas V1 de Alibaba Cloud Object Storage Service se descontinuarán según el siguiente calendario. Actualice a Upgrade to V4 signatures lo antes posible para evitar afectaciones en sus servicios.

  • A partir del 1 de marzo de 2025, los nuevos usuarios no podrán utilizar firmas V1.

  • A partir del 1 de septiembre de 2025, el mantenimiento y las actualizaciones de las firmas V1 se suspenderán gradualmente, y los buckets creados después de esa fecha no admitirán firmas V1.

El siguiente código de ejemplo inicializa un cliente con una firma V1. Para consultar la inicialización con firma V4, véase Initialize the client.

package main

// Sample code for initializing a client with a V1 signature in OSS Go SDK V1

import (
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
	)

	// List all buckets.
	buckets, err := client.ListBuckets()
	if err != nil {
		fmt.Printf("Failed to list buckets: %v\n", err)
		return
	}

	// Print the bucket list.
	fmt.Printf("Found %d buckets:\n", len(buckets.Buckets))

	for _, bucket := range buckets.Buckets {
		fmt.Printf("%s\n", bucket.Name)
	}
}

Establecer el contexto de solicitud

Utilice el contexto de solicitud para controlar el ciclo de vida de las peticiones.

Solo OSS Go SDK 2.2.9 y versiones posteriores admiten la configuración del contexto de solicitud.
package main

// Sample code for setting the request context in OSS Go SDK V1

import (
	"context"
	"fmt"
	"time"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, _ := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)

	// Get the bucket object.
	bucket, _ := client.Bucket("example-bucket-hz")

	// Configure object information.
	key := "oss-browser2-mac-arm64-2.1.0.dmg"       // The path of the object in OSS.
	file_path := "oss-browser2-mac-arm64-2.1.0.dmg" // The local path to save the object.

	// Set the request context.
	ctx := context.Background()

	// Specify that the request context expires in 5 seconds.
	ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	// Download the object from OSS to the specified local path and set the request context.
	err := bucket.GetObjectToFile(key, file_path, oss.WithContext(ctx))
	if err != nil {
		select {
		case <-ctx.Done():
			fmt.Printf("Request canceled or timed out: %v\n", err)
		default:
			fmt.Printf("Download failed: %v\n", err)
		}
		return
	}

	fmt.Printf("Object downloaded: %s -> %s\n", key, file_path)
}

Manejo de errores

Cuando ocurre un error durante el acceso a OSS, el SDK devuelve detalles que incluyen el código de estado HTTP, el mensaje de error, el ID de solicitud y el código de error EC. El código de error EC identifica la causa específica y facilita la resolución rápida del problema. Por ejemplo, si intenta descargar un objeto que no existe, se devolverá el siguiente mensaje de error:

oss: service returned error: StatusCode=404, ErrorCode=NoSuchKey, ErrorMessage="The specified key does not exist.", RequestId=69030EDB2E5F223030953167, Ec=0026-00000001

En el mensaje de error, 'EC': '0026-00000001' corresponde al código de error EC. Puede utilizar este código para identificar la causa del problema y su solución.

Código de ejemplo

OSS Go SDK V1 proporciona código de ejemplo que cubre funciones principales como la gestión de buckets, operaciones con objetos, control de acceso y transferencia cifrada. La siguiente tabla enumera los ejemplos disponibles:

Código de ejemplo en GitHub

Código de ejemplo en la documentación oficial

new_bucket.go

Initialize a client

create_bucket.go

Create a bucket (Go SDK V1)

bucket_acl.go

Manage bucket ACLs (Go SDK V1)

bucket_policy.go

Authorization policy

bucket_referer.go

Hotlink protection (Go SDK V1)

bucket_lifecycle.go

Lifecycle

bucket_logging.go

Access log

bucket_cors.go

Cross-origin access

bucket_website.go

Static website hosting (mirroring-based back-to-origin) (Go SDK V1)

bucket_encryption.go

Server-side encryption (Go SDK V1)

bucket_requestpayment.go

Pay-by-requester (Go SDK V1)

bucket_inventory.go

Bucket inventory (Go SDK V1)

bucket_accessmonitor.go

Access tracking (Go SDK V1)

bucket_metaquery.go

Data indexing (Go SDK V1)

list_buckets.go

List buckets (Go SDK V1)

bucket_stat.go

Obtain the storage capacity of a bucket (Go SDK V1)

bucket_tagging.go

Bucket tagging (Go SDK V1)

put_object.go

Carga de objetos, incluidos simple upload (Go SDK V1) y resumable upload (Go SDK V1)

append_object.go

Append upload

get_object.go

Descarga de objetos, incluidas streaming download (Go SDK V1) y conditional download (Go SDK V1)

delete_object.go

Delete objects (Go SDK V1)

copy_object.go

Copy objects (Go SDK V1)

list_objects.go

List objects (Go SDK V1)

archive.go

Restore objects (Go SDK V1)

object_acl.go

Manage object ACLs

sign_url.go

Upload objects using signed URLs (Go SDK V1)

object_tagging.go

Object tagging

select_object.go

Query objects (Go SDK V1)

object_meta.go

Manage object metadata (Go SDK V1)

livechannel.go

LiveChannel management (Go SDK V1)

Consultar información de endpoints

OSS Go SDK V1 permite consultar información de endpoints para todas las regiones o para regiones específicas, incluidos endpoints públicos (IPv4), endpoints internos (red clásica o VPC) y endpoints de aceleración.

Nota

Go SDK 2.2.8 y versiones posteriores admiten la consulta de información de endpoints.

package main

// Sample code for querying endpoint information in OSS Go SDK V1

import (
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {

	fmt.Println("=== Query endpoint information for all supported regions ===\n")

	// Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET.
	provider, _ := oss.NewEnvironmentVariableCredentialsProvider()

	// Create an OSS client instance.
	client, err := oss.New(
		"oss-cn-hangzhou.aliyuncs.com", // The public endpoint of China (Hangzhou) is used as an example.
		"",
		"",
		oss.SetCredentialsProvider(&provider),
		oss.AuthVersion(oss.AuthV4),
		oss.Region("cn-hangzhou"),
	)
	if err != nil {
		fmt.Printf("Failed to create client: %v\n", err)
		return
	}

	// Query endpoint information for all supported regions.
	result, err := client.DescribeRegions()
	if err != nil {
		fmt.Printf("Failed to query endpoint information: %v\n", err)
		return
	}

	// Traverse all region information.
	for _, region := range result.Regions {
		fmt.Printf("Region: %s\n", region.Region)
		fmt.Printf("  Public endpoint (IPv4): %s\n", region.InternetEndpoint)
		fmt.Printf("  Internal endpoint (classic network or VPC): %s\n", region.InternalEndpoint)
		fmt.Printf("  Acceleration endpoint (global upload and download acceleration): %s\n", region.AccelerateEndpoint)
		fmt.Println("--------------------------------------------------------------------------------")
	}

	// Print statistics.
	fmt.Printf("\nFound endpoint information for %d regions\n", len(result.Regions))
}

Para consultar información de endpoints de una región específica, especifique el ID de región correspondiente a OSS en el método DescribeRegions.

result, err := client.DescribeRegions(oss.AddParam("regions", "oss-cn-hangzhou"))

Configuración de credenciales de acceso

OSS admite varios métodos de inicialización de credenciales. Seleccione un método según sus requisitos de autenticación y autorización.

Haga clic para ver cómo seleccionar las credenciales de acceso

Método de inicialización del proveedor de credenciales

Escenarios

Requiere par de AccessKey o token de STS preconfigurado

Credencial subyacente

Validez de la credencial

Método de rotación o actualización de credenciales

Use the AccessKey pair of a RAM user

Aplicaciones desplegadas en un entorno seguro y estable, no susceptible a ataques externos, que requieren acceso a largo plazo a los servicios de Alibaba Cloud sin rotación frecuente de credenciales.

Sí

Par de AccessKey

Largo plazo

Rotación manual

Use STS temporary access credentials

Aplicaciones desplegadas en un entorno no confiable que requieren control sobre el periodo de validez y los permisos de acceso.

Sí

Token de Security Token Service

Temporal

Actualización manual

Use a RAM role ARN

Aplicaciones que requieren acceso autorizado a los servicios de Alibaba Cloud, como el acceso entre cuentas.

Sí

Token de Security Token Service

Temporal

Actualización automática

Use an ECS instance RAM role

Aplicaciones desplegadas en instancias ECS, instancias ECI o nodos worker de Container Service for Kubernetes de Alibaba Cloud.

No

Token de Security Token Service

Temporal

Actualización automática

Use an OIDC role ARN

Aplicaciones no confiables desplegadas en nodos worker de Container Service for Kubernetes de Alibaba Cloud.

No

Token de Security Token Service

Temporal

Actualización automática

Use credentials from the Function Compute context

Funciones de aplicaciones desplegadas en Function Compute de Alibaba Cloud.

No

Token de Security Token Service

Temporal

No requiere actualización

Use a CredentialsURI

Aplicaciones que necesitan obtener credenciales de acceso de un sistema externo.

No

Token de Security Token Service

Temporal

Actualización automática

Use an auto-rotating AccessKey pair

Aplicaciones desplegadas en un entorno con riesgo de fuga del par de AccessKey que requieren rotación frecuente de credenciales para el acceso a largo plazo a los servicios de Alibaba Cloud.

No

Par de AccessKey

Largo plazo

Rotación automática

Use custom access credentials

Si ninguno de los métodos de configuración de credenciales anteriores cumple con sus requisitos, puede personalizar la forma en que obtiene las credenciales.

Personalizado

Personalizado

Personalizado

Personalizado

Uso del par de AccessKey de un usuario de RAM

Adecuado para aplicaciones desplegadas en un entorno seguro que requieren acceso a OSS a largo plazo sin rotación frecuente de credenciales. Inicialice el proveedor de credenciales con el par de AccessKey (AccessKey ID y AccessKey secret) de una cuenta de Alibaba Cloud o de un usuario de RAM. Este método requiere mantenimiento manual del par de AccessKey, lo cual puede introducir riesgos de seguridad.

Importante
  • Una cuenta de Alibaba Cloud tiene permisos completos sobre los recursos. Si el par de AccessKey se filtra, representa un riesgo significativo para su sistema. No se recomienda utilizar el par de AccessKey de una cuenta de Alibaba Cloud. Utilice el par de AccessKey de un usuario de RAM con los permisos mínimos necesarios.

  • Para crear un par de AccessKey para un usuario de RAM, consulte Create an AccessKey pair. El AccessKey ID y el AccessKey secret de un usuario de RAM solo se muestran cuando se crea el par de AccessKey. Si los olvida, cree un nuevo par de AccessKey para reemplazar el anterior.

Variables de entorno

  1. Configure las variables de entorno mediante el par de AccessKey de un usuario de RAM.

    Linux

    1. Ejecute los siguientes comandos en la interfaz de línea de comandos para agregar la configuración de variables de entorno al archivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
    2. Ejecute el siguiente comando para aplicar los cambios.

      source ~/.bashrc
    3. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.

      echo $OSS_ACCESS_KEY_ID
      echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Ejecute el siguiente comando en la terminal para ver el tipo de shell predeterminado.

      echo $SHELL
    2. Realice las siguientes operaciones según el tipo de shell predeterminado.

      Zsh

      1. Ejecute los siguientes comandos para agregar la configuración de variables de entorno al archivo ~/.zshrc.

        echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
      2. Ejecute el siguiente comando para aplicar los cambios.

        source ~/.zshrc
      3. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

      Bash

      1. Ejecute los siguientes comandos para agregar la configuración de variables de entorno al archivo ~/.bash_profile.

        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. Ejecute el siguiente comando para aplicar los cambios.

        source ~/.bash_profile
      3. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Ejecute los siguientes comandos en CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
    2. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.

      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Ejecute los siguientes comandos en PowerShell.

      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
    2. Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.

      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
      [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Después de modificar las variables de entorno del sistema, reinicie o actualice el entorno de compilación y ejecución. Esto incluye IDE, interfaces de línea de comandos, otras aplicaciones de escritorio y servicios de backend para asegurar que se carguen las variables de entorno más recientes del sistema.

  3. Utilice variables de entorno para pasar la información de las credenciales.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
    	// 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.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Credenciales estáticas

Para evitar codificar las credenciales directamente en el código fuente, refiéncelas mediante variables que lean desde variables de entorno, archivos de configuración u otras fuentes externas en tiempo de ejecución. El siguiente ejemplo utiliza un archivo de configuración:

  1. Instale la biblioteca go-ini.

    go get -u github.com/go-ini/ini
  2. Cree un archivo de configuración llamado config.ini.

    [credentials]
    alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID>
    alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
  3. Escriba código para leer la información de las credenciales desde el archivo de configuración e inicializar el cliente de OSS.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"gopkg.in/ini.v1"
    )
    
    type defaultCredentials struct {
    	config *oss.Config
    }
    
    func (defCre *defaultCredentials) GetAccessKeyID() string {
    	return defCre.config.AccessKeyID
    }
    
    func (defCre *defaultCredentials) GetAccessKeySecret() string {
    	return defCre.config.AccessKeySecret
    }
    
    func (defCre *defaultCredentials) GetSecurityToken() string {
    	return defCre.config.SecurityToken
    }
    
    type defaultCredentialsProvider struct {
    	config *oss.Config
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	return &defaultCredentials{config: defBuild.config}
    }
    func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) {
    	var provider defaultCredentialsProvider
    	if accessID == "" {
    		return provider, fmt.Errorf("access key id is empty!")
    	}
    	if accessKey == "" {
    		return provider, fmt.Errorf("access key secret is empty!")
    	}
    	config := &oss.Config{
    		AccessKeyID:     accessID,
    		AccessKeySecret: accessKey,
    		SecurityToken:   token,
    	}
    	return defaultCredentialsProvider{
    		config,
    	}, nil
    }
    
    func main() {
    	cfg, err := ini.Load("config.ini")
    	if err != nil {
    		fmt.Println("Error loading config file:", err)
    		return
    	}
    	accessKeyID := cfg.Section("credentials").Key("alibaba_cloud_access_key_id").String()
    	accessKeySecret := cfg.Section("credentials").Key("alibaba_cloud_access_key_secret").String()
    	provider, err := NewDefaultCredentialsProvider(accessKeyID, accessKeySecret, "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Uso de credenciales de acceso temporal de STS

Adecuado para aplicaciones que necesitan acceso temporal a OSS. Inicialice el proveedor de credenciales con credenciales temporales (AccessKey ID, AccessKey secret y Security Token) obtenidas de STS. Este método requiere mantenimiento manual del token de STS. Para acceder a OSS varias veces, debe actualizar manualmente el token antes de que caduque.

Importante
  1. Establezca variables de entorno utilizando las credenciales de identidad temporales.

    Mac OS/Linux/Unix

    Importante
    • Utilice las credenciales de identidad temporales (AccessKey ID, AccessKey secret y Security Token) obtenidas de STS, no el par de AccessKey (AccessKey ID y AccessKey secret) de un usuario de RAM.

    • El AccessKey ID obtenido de STS comienza con "STS.", por ejemplo, "STS.".

    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

    Importante
    • Utilice las credenciales de identidad temporales (AccessKey ID, AccessKey secret y Security Token) obtenidas de STS, no el par de AccessKey (AccessKey ID y AccessKey secret) de un usuario de RAM.

    • El AccessKey ID obtenido de STS comienza con "STS.", por ejemplo, "STS.".

    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. Pase la información de las credenciales a través de variables de entorno.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    )
    
    func main() {
    	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are set.
    	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Create an OSSClient instance.
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Uso de un ARN de rol de RAM

Adecuado para aplicaciones que requieren acceso autorizado a OSS, como el acceso entre cuentas. Inicialice el proveedor de credenciales especificando el ARN de un rol de RAM. La herramienta Credentials obtiene automáticamente tokens de STS y los actualiza antes de que caduquen llamando a la operación AssumeRole. También puede asignar una policy para restringir el rol a un conjunto menor de permisos.

Importante
  • Una cuenta de Alibaba Cloud tiene permisos completos sobre los recursos. Si el par de AccessKey se filtra, representa un riesgo significativo para su sistema. No se recomienda utilizar el par de AccessKey de una cuenta de Alibaba Cloud. Utilice el par de AccessKey de un usuario de RAM con los permisos mínimos necesarios.

  • Para crear un par de AccessKey para un usuario de RAM, consulte Create an AccessKey pair. El AccessKey ID y el AccessKey secret de un usuario de RAM solo se muestran cuando se crea el par de AccessKey. Guárdelos de inmediato. Si los olvida, cree un nuevo par de AccessKey para reemplazar el anterior.

  • Para obtener un ARN de rol de RAM, consulte Create a RAM role.

  1. Agregue la dependencia de credenciales.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure el par de AccessKey y el ARN de rol de RAM como credenciales de acceso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type defaultCredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewRamRoleArnCredentialsProvider(credential credentials.Credential) defaultCredentialsProvider {
    	return defaultCredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to ram_role_arn.
    		SetType("ram_role_arn").
    		// The AccessKey ID and AccessKey secret of the RAM user. The values are obtained from environment variables.
    		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
    		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
    		// The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters.
    		// The ARN of the RAM role to assume. The value is obtained from an environment variable. Format: acs:ram::$accountID:role/$roleName.
    		SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN.
    		// A custom name for the role session to distinguish different tokens.
    		SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    		// (Optional) Restrict the permissions of the STS token.
    		SetPolicy("").
    		// (Optional) Limit the validity period of the STS token.
    		SetRoleSessionExpiration(3600)
    
    	arnCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	provider := NewRamRoleArnCredentialsProvider(arnCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    
    	fmt.Printf("client:%#v\n", client)
    }

Uso de un rol de RAM de instancia ECS

Recomendado para aplicaciones que se ejecutan en instancias ECS, instancias ECI o nodos worker de Container Service for Kubernetes. Un rol de RAM de instancia ECS asocia un rol con la instancia, lo que permite la actualización automática del token de STS sin proporcionar un par de AccessKey ni un token de STS. Para obtener información sobre cómo conseguir un rol de RAM de instancia ECS, consulte Create a RAM role. Para obtener información sobre cómo asociar un rol con una instancia ECS, consulte Instance RAM roles.

  1. Agregue la dependencia de credenciales.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure el rol de RAM de instancia ECS como credencial de acceso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewEcsCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to ecs_ram_role.
    		SetType("ecs_ram_role").
    		// (Optional) The role name. If you do not specify this parameter, OSS automatically obtains the role. We recommend that you specify the role name to reduce the number of requests.
    		SetRoleName("RoleName")
    
    	ecsCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewEcsCredentialsProvider(ecsCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    
    }

Uso de un ARN de rol OIDC

Para aplicaciones no confiables desplegadas en nodos worker de Container Service for Kubernetes, la función RAM Roles for Service Accounts (RRSA) proporciona aislamiento de credenciales a nivel de pod. En lugar de compartir el rol de RAM de instancia del nodo worker a través del servicio de metadatos global, RRSA monta un archivo de token OIDC de cuenta de servicio en cada pod e inyecta la configuración en las variables de entorno. Luego, la herramienta Credentials llama a la operación AssumeRoleWithOIDC para intercambiar el token OIDC por un token de STS. No se requiere ningún par de AccessKey ni token de STS. Para obtener más información, consulte Configure RAM permissions for a ServiceAccount using RRSA to achieve pod-level permission isolation.

  1. Agregue la dependencia de credenciales.

    go get github.com/aliyun/credentials-go/credentials
  2. Configure el rol de RAM OIDC como credencial de acceso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewOIDCRoleARNCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The file path of the OIDC token.
    		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
    		// The following operations directly use parameter values. You can also add environment variables and use os.Getenv("<variable_name>") to set the corresponding parameters.
    		// The credential type. Set the value to oidc_role_arn.
    		SetType("oidc_role_arn").
    		// The ARN of the OIDC provider. Format: acs:ram::account-id:oidc-provider/provider-name.
    		SetOIDCProviderArn("acs:ram::113511544585****:oidc-provider/TestOidcProvider"). // The standard environment variable name for OIDCProviderArn is ALIBABA_CLOUD_OIDC_PROVIDER_ARN.
    		// A custom name for the role session to distinguish different tokens.
    		SetRoleSessionName("role_session_name"). // The standard environment variable name for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    		// The ARN of the role to assume. Format: acs:ram::113511544585****:oidc-provider/TestOidcProvider
    		SetRoleArn("acs:ram::113511544585****:role/testoidc"). // The standard environment variable name for RoleArn is ALIBABA_CLOUD_ROLE_ARN.
    		// (Optional) The policy to use when assuming the role.
    		SetPolicy("").
    		SetSessionExpiration(3600)
    	oidcCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewOIDCRoleARNCredentialsProvider(oidcCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Uso de credenciales del contexto de Function Compute

Adecuado para funciones de aplicaciones desplegadas en Function Compute. Function Compute obtiene un token de STS asumiendo el rol de servicio configurado para la función y lo pasa a través del parámetro Credentials en el contexto. Este token de STS es válido durante 36 horas y no caduca durante la ejecución de la función (máximo 24 horas), por lo que no es necesario actualizarlo. No se requiere ningún par de AccessKey ni token de STS. Para obtener información sobre cómo otorgar permisos a Function Compute para acceder a OSS, consulte Use a function role to grant Function Compute permissions to access other Alibaba Cloud services.

  1. Agregue las dependencias del contexto de Function Compute.

    go get github.com/aliyun/fc-runtime-go-sdk/fc
    go get github.com/aliyun/fc-runtime-go-sdk/fccontext
  2. Inicialice el proveedor de credenciales utilizando las credenciales del contexto de Function Compute.

    package main
    
    import (
    	"context"
    	"fmt"
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/fc-runtime-go-sdk/fc"
    	"github.com/aliyun/fc-runtime-go-sdk/fccontext"
    )
    
    type GetObjectContext struct {
    	OutputRoute string `json:"outputRoute"`
    	OutputToken string `json:"outputToken"`
    	InputOssUrl string `json:"inputOssUrl"`
    }
    
    type StructEvent struct {
    	GetObjectContext GetObjectContext `json:"getObjectContext"`
    }
    
    func HandleRequest(ctx context.Context, event StructEvent) error {
    	endpoint := event.GetObjectContext.OutputRoute
    	fctx, _ := fccontext.FromContext(ctx)
    	client, err := oss.New(endpoint, fctx.Credentials.AccessKeyId, fctx.Credentials.AccessKeySecret, oss.SecurityToken(fctx.Credentials.SecurityToken))
    	if err != nil {
    		return fmt.Errorf("client new error: %v", err)
    	}
    	fmt.Printf("client:%#v\n", client)
    	return nil
    }
    
    func main() {
    	fc.Start(HandleRequest)
    }

Uso de CredentialsURI

Adecuado para aplicaciones que obtienen credenciales de un sistema externo. La herramienta Credentials recupera tokens de STS de la URI especificada y los actualiza automáticamente. No se requiere ningún par de AccessKey ni token de STS.

Importante
  • CredentialsURI es la dirección del servidor desde la cual se obtiene el token de STS.

  • El servicio de backend que proporciona la respuesta de CredentialsURI debe implementar la lógica para la actualización automática del token de STS con el fin de garantizar que la aplicación siempre pueda obtener credenciales válidas.

  1. Para que la herramienta Credentials analice y utilice correctamente el token de STS, la URI debe cumplir con el siguiente protocolo de respuesta:

    • Código de estado de respuesta: 200

    • Estructura del cuerpo de respuesta:

      {
          "Code": "Success",
          "AccessKeySecret": "AccessKeySecret",
          "AccessKeyId": "AccessKeyId",
          "Expiration": "2021-09-26T03:46:38Z",
          "SecurityToken": "SecurityToken"
      }
  2. Agregue la dependencia de credenciales.

    go get github.com/aliyun/credentials-go/credentials
  3. Configure CredentialsURI como credencial de acceso.

    package main
    
    import (
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/credentials-go/credentials"
    )
    
    type Credentials struct {
    	AccessKeyId     string
    	AccessKeySecret string
    	SecurityToken   string
    }
    
    type CredentialsProvider struct {
    	cred credentials.Credential
    }
    
    func (credentials *Credentials) GetAccessKeyID() string {
    	return credentials.AccessKeyId
    }
    
    func (credentials *Credentials) GetAccessKeySecret() string {
    	return credentials.AccessKeySecret
    }
    
    func (credentials *Credentials) GetSecurityToken() string {
    	return credentials.SecurityToken
    }
    
    func (defBuild CredentialsProvider) GetCredentials() oss.Credentials {
    	cred, _ := defBuild.cred.GetCredential()
    	return &Credentials{
    		AccessKeyId:     *cred.AccessKeyId,
    		AccessKeySecret: *cred.AccessKeySecret,
    		SecurityToken:   *cred.SecurityToken,
    	}
    }
    
    func NewCredentialsUriCredentialsProvider(credential credentials.Credential) CredentialsProvider {
    	return CredentialsProvider{
    		cred: credential,
    	}
    }
    
    func main() {
    	config := new(credentials.Config).
    		// The credential type. Set the value to credentials_uri.
    		SetType("credentials_uri").
    		// Specify the URL address. You can also set an environment variable and use os.Getenv("<variable_name>") to pass the parameter.
    		// The standard environment variable name for URLCredential is ALIBABA_CLOUD_CREDENTIALS_URI.
    		SetURLCredential("http://127.0.0.1")
    	uriCredential, err := credentials.NewCredential(config)
    	if err != nil {
    		return
    	}
    	provider := NewCredentialsUriCredentialsProvider(uriCredential)
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", client)
    }

Uso de un par de AccessKey con rotación automática

Adecuado para aplicaciones que requieren acceso a OSS a largo plazo pero que están desplegadas en entornos donde existe riesgo de fuga del par de AccessKey. Inicialice el proveedor de credenciales con una ClientKey. Key Management Service (KMS) rota automáticamente el par de AccessKey del usuario de RAM administrado según un programa periódico, convirtiendo una credencial estática en una dinámica. KMS también admite la rotación inmediata para un reemplazo rápido en caso de fuga. Para obtener información sobre cómo conseguir una ClientKey, consulte Create an application access point.

  1. Agregue la dependencia del cliente de credenciales.

    go get -u github.com/aliyun/aliyun-secretsmanager-client-go
  2. Cree un archivo de configuración llamado secretsmanager.properties.

    # Access credential type
    credentials_type=client_key
    
    # The password used to decrypt the client key. The password can be read from an environment variable or a file.
    client_key_password_from_env_variable=#your client key private key password environment variable name#
    client_key_password_from_file_path=#your client key private key password file path#
    
    # The path of the client key's private key file.
    client_key_private_key_path=#your client key private key file path#
    
    # The region of the associated KMS service.
    cache_client_region_id=[{"regionId":"#regionId#"}]
  3. Utilice el archivo de configuración para pasar la información de las credenciales.

    package main
    
    import (
    	"encoding/json"
    	"fmt"
    	"os"
    
    	"github.com/aliyun/aliyun-oss-go-sdk/oss"
    	"github.com/aliyun/aliyun-secretsmanager-client-go/sdk"
    )
    
    type defaultCredentials struct {
    	config *oss.Config
    }
    
    func (defCre *defaultCredentials) GetAccessKeyID() string {
    	return defCre.config.AccessKeyID
    }
    
    func (defCre *defaultCredentials) GetAccessKeySecret() string {
    	return defCre.config.AccessKeySecret
    }
    
    func (defCre *defaultCredentials) GetSecurityToken() string {
    	return defCre.config.SecurityToken
    }
    
    type defaultCredentialsProvider struct {
    	config *oss.Config
    }
    
    func (defBuild *defaultCredentialsProvider) GetCredentials() oss.Credentials {
    	return &defaultCredentials{config: defBuild.config}
    }
    func NewDefaultCredentialsProvider(accessID, accessKey, token string) (defaultCredentialsProvider, error) {
    	var provider defaultCredentialsProvider
    	if accessID == "" {
    		return provider, fmt.Errorf("access key id is empty!")
    	}
    	if accessKey == "" {
    		return provider, fmt.Errorf("access key secret is empty!")
    	}
    	config := &oss.Config{
    		AccessKeyID:     accessID,
    		AccessKeySecret: accessKey,
    		SecurityToken:   token,
    	}
    	return defaultCredentialsProvider{
    		config,
    	}, nil
    }
    
    func main() {
    	client, err := sdk.NewClient()
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	secretInfo, err := client.GetSecretInfo("#secretName#")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("SecretValue:%s\n", secretInfo.SecretValue)
    	var m map[string]string
    	err = json.Unmarshal([]byte(secretInfo.SecretValue), &m)
    	if err != nil {
    		fmt.Println("Error decoding JSON:", err)
    		os.Exit(-1)
    	}
    	accessKeyId := m["AccessKeyId"]
    	accessKeySecret := m["AccessKeySecret"]
    	provider, err := NewDefaultCredentialsProvider(accessKeyId, accessKeySecret, "")
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
    	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
    	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
    	clientOptions = append(clientOptions, oss.Region("yourRegion"))
    	// Set the signature version.
    	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
    	ossClient, err := oss.New("yourEndpoint", "", "", clientOptions...)
    	if err != nil {
    		fmt.Println("Error:", err)
    		os.Exit(-1)
    	}
    	fmt.Printf("client:%#v\n", ossClient)
    }

Uso de credenciales de acceso personalizadas

Si ninguno de los métodos anteriores cumple con sus requisitos, puede implementar un proveedor de credenciales personalizado utilizando la interfaz Credential Providers. Si las credenciales subyacentes se basan en STS, debe gestionar la actualización del token.

package main

import (
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type CustomerCredentialsProvider struct {
	config *oss.Config
}

func NewCustomerCredentialsProvider() CustomerCredentialsProvider {
	return CustomerCredentialsProvider{}
}

func (s CustomerCredentialsProvider) GetCredentials() oss.Credentials {
	// Return long-term credentials.
	config := &oss.Config{
		AccessKeyID:     "id",
		AccessKeySecret: "secret",
	}
	return &CustomerCredentialsProvider{
		config,
	}
	// Return temporary credentials.
	//config := &oss.Config{
	//    AccessKeyID:     "id",
	//    AccessKeySecret: "secret",
	//    SecurityToken:   "token",
	//}
	//return &CustomerCredentialsProvider{
	//    config,
	//}
}

func (s *CustomerCredentialsProvider) GetAccessKeyID() string {
	return s.config.AccessKeyID
}

func (s *CustomerCredentialsProvider) GetAccessKeySecret() string {
	return s.config.AccessKeySecret
}

func (s *CustomerCredentialsProvider) GetSecurityToken() string {
	return s.config.SecurityToken
}

func main() {
	provider := NewCustomerCredentialsProvider()
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the endpoint as needed.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Printf("client:%#v\n", client)
}

Preguntas frecuentes

¿Cómo soluciono el error AccessDenied al usar el SDK?

El error AccessDenied generalmente indica permisos insuficientes. Siga estos pasos para solucionarlo:

  1. Confirme el AccessKey ID y el AccessKey secret: asegúrese de utilizar el AccessKey ID y el AccessKey secret correctos.

  2. Revise los permisos del usuario de RAM: compruebe si el usuario de RAM cuenta con los permisos necesarios para las operaciones de bucket u objeto.

  3. Verifique la directiva del bucket: si el mensaje de error menciona "Access denied by bucket policy", significa que una directiva de bucket denegó el acceso.

  4. Para obtener más información sobre cómo consultar otros tipos de errores y solucionar problemas comunes de control de acceso, consulte Error handling.

Referencias