Todos los productos
Search
Centro de documentos

:Configurar credenciales de acceso con OSS SDK for Python 1.0

Última actualización: Sep 25, 2026

Para iniciar una solicitud con Object Storage Service (OSS) SDK for Python, debe configurar las credenciales de acceso. Estas credenciales sirven para verificar su identidad y sus permisos de acceso. Seleccione distintos tipos de credenciales de acceso según sus requisitos de autenticación y autorización.

Notas de uso

  • Consulte Regions and endpoints para ver la lista de regiones y endpoints de OSS.

  • Consulte Create an AccessKey pair for a RAM user para obtener información sobre cómo crear un par de AccessKey para un usuario de RAM.

  • Antes de configurar las credenciales de acceso, asegúrese de que tiene instalada la versión más reciente de OSS SDK for Python. Para más información, consulte Installation.

  • Asegúrese de que la versión de alibabacloud-credentials sea la 0.3.5 o posterior. Las versiones anteriores generan errores.

Inicialización del proveedor de credenciales

OSS admite varios métodos para inicializar un proveedor de credenciales. Seleccione el método adecuado según sus necesidades reales de autenticación y autorización.

Método de inicialización

Escenario

¿Se requiere un par de AccessKey o un token de STS?

Credencial subyacente

Periodo de validez de la credencial

Método de rotación o actualización de la credencial

Use the AccessKey pair of a RAM user

Las aplicaciones se despliegan y ejecutan en un entorno seguro y estable, no vulnerable a ataques externos. Además, necesitan acceso a largo plazo a los servicios en la nube sin rotar las credenciales con frecuencia.

Sí

Par de AccessKey

Largo plazo

Rotación manual

Use temporary access credentials provided by STS

Las aplicaciones se despliegan y ejecutan en un entorno no confiable. En este caso, conviene controlar la validez de la credencial y los recursos a los que se puede acceder.

Sí

Token de Security Token Service (STS)

Temporal

Actualización manual

Use the ARN of a RAM role

Las aplicaciones requieren acceso a servicios en la nube, por ejemplo, acceso entre cuentas.

Sí

Token de STS

Temporal

Actualización automática

Use the RAM role of an ECS instance

Las aplicaciones se despliegan y ejecutan en instancias de Elastic Compute Service (ECS), Elastic Container Instance o nodos worker de Container Service for Kubernetes (ACK).

No

Token de STS

Temporal

Actualización automática

Use the role of an OIDC IdP

Aplicaciones no confiables desplegadas y ejecutadas en nodos worker de ACK.

No

Token de STS

Temporal

Actualización automática

Use the Credentials parameter in the context of Function Compute

Las funciones de sus aplicaciones se despliegan y ejecutan en Function Compute.

No

Token de STS

Temporal

No es necesario actualizar

Use the CredentialsURI

Las aplicaciones necesitan credenciales de acceso provenientes de sistemas externos.

No

Token de STS

Temporal

Actualización automática

Use an AccessKey pair that automatically rotates

Las aplicaciones se despliegan en un entorno donde el par de AccessKey corre alto riesgo de filtración. Requieren rotar las credenciales de acceso con frecuencia para mantener el acceso a largo plazo a los servicios en la nube.

No

Par de AccessKey

Largo plazo

Rotación automática

Use custom access credentials

Si ninguno de los métodos anteriores cumple con sus requisitos, utilice un método personalizado para obtener las credenciales de acceso.

Personalizado

Personalizado

Personalizado

Personalizado

Ejemplos de configuración para escenarios comunes

Usar el par de AccessKey de un usuario de RAM

Suponga que su aplicación necesita acceso a largo plazo a OSS sin rotar las credenciales de acceso con frecuencia. Además, se ejecuta en un entorno seguro y estable, no vulnerable a ataques externos. En este caso, utilice un par de AccessKey (un AccessKey ID y un AccessKey secret) de su cuenta de Alibaba Cloud o de un usuario de RAM para inicializar un proveedor de credenciales. Tenga en cuenta que este método exige mantener manualmente el par de AccessKey, lo cual implica riesgos de seguridad y aumenta la complejidad del mantenimiento.

Aviso
  • Una cuenta de Alibaba Cloud tiene permisos totales sobre sus recursos. La filtración de su par de AccessKey representa un riesgo de seguridad importante. Por ello, se recomienda usar el par de AccessKey de un usuario de RAM con los permisos mínimos necesarios para inicializar el proveedor de credenciales.

  • Consulte Create an AccessKey pair for a RAM user para saber cómo crear un par de AccessKey para un usuario de RAM. El par de AccessKey de un usuario de RAM solo se muestra cuando se crea dicho usuario. Guarde el par de AccessKey de inmediato. Si lo olvida, cree uno nuevo para rotarlo.

Variables de entorno

  1. Configure las variables de entorno para el par de AccessKey del usuario de RAM.

    Linux

    1. Ejecute los siguientes comandos en la interfaz de línea de comandos para agregar la configuración de las 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
      1. Ejecute el siguiente comando para aplicar los cambios.

        source ~/.bashrc
      2. Ejecute el siguiente comando para comprobar si las variables de entorno están activas.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

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

      echo $SHELL
      1. Realice las operaciones correspondientes según el tipo de shell predeterminado.

        Zsh

        1. Ejecute los siguientes comandos para agregar la configuración de las 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 el siguiente comando para comprobar si las variables de entorno están activas.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Ejecute los siguientes comandos para agregar la configuración de las 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 el siguiente comando para comprobar si las variables de entorno están activas.

          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"
      1. Ejecute el siguiente comando para comprobar si las variables de entorno están activas.

        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)
      1. Ejecute el siguiente comando para comprobar si las variables de entorno están activas.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Reinicie o actualice sus entornos de compilación y ejecución para asegurarse de que la configuración se cargue correctamente. Esto aplica a IDE, herramientas de línea de comandos, aplicaciones de escritorio y servicios en segundo plano.

  3. Pase las credenciales mediante variables de entorno.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the AccessKey pair of the RAM user obtained from the environment variables to configure access credentials. Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.

Credenciales estáticas

El siguiente ejemplo muestra cómo codificar de forma fija las credenciales de acceso de un usuario de RAM en el código:

Aviso

No inserte credenciales de acceso en el código de aplicaciones desplegadas en un entorno de producción. Este método está diseñado únicamente para pruebas.

# -*- coding: utf-8 -*-
import oss2

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the name of the bucket. 
bucket_name = 'yourBucketName'

# Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
region = 'cn-hangzhou'

# Enter the AccessKey ID and AccessKey secret of the RAM user.
access_key_id = 'yourAccessKeyID'
access_key_secret = 'yourAccessKeySecret'

# Use the AccessKey pair of the RAM user as access credentials. Note that AuthV4 indicates that the signature algorithm V4 is used. 
auth = oss2.AuthV4(access_key_id, access_key_secret)

# Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

Usar credenciales de acceso temporales proporcionadas por STS

Si su aplicación necesita acceder a OSS de forma temporal, utilice las credenciales de acceso temporales que proporciona STS. Estas credenciales constan de un par de AccessKey y un token de STS. Tenga en cuenta que este método exige mantener manualmente el token de STS, lo cual implica riesgos de seguridad y aumenta la complejidad del mantenimiento. Si desea prolongar el acceso después de que expire el token de STS actual, debe actualizarlo manualmente.

Importante
  • Obtenga las credenciales de acceso temporales mediante la llamada a la operación de API AssumeRole. Para más información, consulte AssumeRole.

  • También puede obtener las credenciales de acceso temporales con el SDK. Para más información, consulte Access OSS by using STS temporary credentials.

  • Debe especificar un periodo de validez para el token de STS al generarlo. Un token de STS caducado no se puede utilizar.

  • Consulte Endpoints para ver la lista de endpoints de STS.

Variables de entorno

  1. Configure las variables de entorno para las credenciales de acceso temporales.

    Mac OS X/Linux/Unix

    Aviso
    • Tenga en cuenta que se utilizan las credenciales de acceso temporales (AccessKey ID, AccessKey secret y token de STS) proporcionadas por STS, en lugar del AccessKey ID y el AccessKey secret del usuario de RAM.

    • El AccessKey ID proporcionado por 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

    Aviso
    • Tenga en cuenta que se utilizan las credenciales de acceso temporales (AccessKey ID, AccessKey secret y token de STS) proporcionadas por STS, en lugar del par de AccessKey (AccessKey ID y AccessKey secret) del usuario de RAM.

    • El AccessKey ID proporcionado por 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 mediante variables de entorno.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2.credentials import EnvironmentVariableCredentialsProvider
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the AccessKey ID, AccessKey secret, and STS token as access credentials. ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.

Credenciales estáticas

El siguiente ejemplo muestra cómo codificar de forma fija las credenciales de acceso temporales en el código:

Aviso

No inserte credenciales de acceso en el código de aplicaciones desplegadas en un entorno de producción. Este método está diseñado únicamente para pruebas.

# -*- coding: utf-8 -*-
import oss2

# Specify the temporary AccessKey ID and AccessKey secret provided by STS, instead of the AccessKey ID and AccessKey secret of an Alibaba Cloud account. 
# Note that an AccessKey ID provided by STS starts with STS. 
sts_access_key_id = 'STS.****************'
sts_access_key_secret = 'yourAccessKeySecret'
# Specify the STS token obtained from STS. 
security_token = 'yourSecurityToken'

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the name of the bucket. 
bucket_name = 'yourBucketName'

# Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
region = 'cn-hangzhou'

# Initialize the StsAuth instance. Note that auth_version is set to v4, indicating that the signature algorithm V4 is used. 
auth = oss2.StsAuth(sts_access_key_id,
                    sts_access_key_secret,
                    security_token,
                    auth_version="v4")

# Use the StsAuth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.

Ejemplos de configuración para otros escenarios

Usar el ARN de un rol de RAM

Si necesita autorizar a su aplicación para acceder a OSS, por ejemplo, en un escenario de acceso entre cuentas, utilice el nombre de recurso de Alibaba Cloud (ARN) de un rol de RAM para inicializar un proveedor de credenciales. La lógica subyacente de este método consiste en usar un token de STS obtenido de STS para configurar las credenciales de acceso. La herramienta Credentials obtiene un token de STS a partir del ARN del rol de RAM. Luego, actualiza el token de STS mediante la llamada a la operación AssumeRole antes de que la sesión expire. Especifique una policy para limitar los permisos otorgados al rol de RAM.

Importante
  • Una cuenta de Alibaba Cloud tiene permisos totales sobre sus recursos. La filtración de su par de AccessKey representa un riesgo de seguridad importante. Por ello, se recomienda usar el par de AccessKey de un usuario de RAM con los permisos mínimos necesarios para inicializar el proveedor de credenciales.

  • Consulte Create an AccessKey pair for a RAM user para saber cómo crear un par de AccessKey para un usuario de RAM. El par de AccessKey de un usuario de RAM solo se muestra cuando se crea dicho usuario. Guarde el par de AccessKey de inmediato. Si lo olvida, cree uno nuevo para rotarlo.

  • Cree un rol de RAM mediante la llamada a la operación CreateRole. El ARN del rol de RAM se incluye en la respuesta. Para más información, consulte CreateRole.

  1. Agregue la dependencia alibabacloud_credentials.

    pip install alibabacloud_credentials
  2. Configure el par de AccessKey y RAMRoleARN como credenciales de acceso.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    import os
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        # Obtain the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user from environment variables.
        access_key_id=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        access_key_secret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
        type='ram_role_arn',
        # Specify the ARN of the RAM role that you want your application to assume by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole
        role_arn='<RoleArn>',
        # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        role_session_name='<RoleSessionName>',
        # (Optional) Specify limited permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy='<Policy>',
        # (Optional) Specify the validity period of the role session.
        role_session_expiration=3600
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Usar el rol de RAM de una instancia de ECS

Si su aplicación se ejecuta en una instancia de ECS, una instancia de contenedor elástico o un nodo worker de ACK, se recomienda usar el rol de RAM de la instancia de ECS para inicializar un proveedor de credenciales. La lógica subyacente de este método consiste en usar un token de STS obtenido de STS para configurar las credenciales de acceso. Asigne un rol de RAM a una instancia de ECS, una instancia de contenedor elástico o un nodo worker de ACK para actualizar automáticamente el token de STS en la instancia. Este método no requiere un par de AccessKey ni un token de STS, lo cual elimina los riesgos asociados con la gestión manual de estas credenciales. Cree un rol de RAM mediante la llamada a la operación CreateRole. El ARN se incluye en la respuesta. Para más información, consulte CreateRole.

  1. Agregue la dependencia alibabacloud_credentials.

    pip install alibabacloud_credentials
  2. Utilice el rol de RAM para proporcionar las credenciales de acceso.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        type='ecs_ram_role',      # Specify the credential type. Set the value to ecs_ram_role. 
        role_name='<RoleName>'    # Specify the name of the RAM role that is attached to the ECS instance. The RAM role name is optional. If you do not configure this parameter, the system automatically searches for a RAM role. We recommend that you configure this parameter to reduce the number of requests. 
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Usar el rol de un IdP de OIDC

Una vez configurado el rol de RAM en el nodo worker de ACK, las aplicaciones dentro de los pods de ese nodo pueden recuperar el token de STS del rol asignado mediante el servidor de metadatos. Este proceso es similar al de una aplicación desplegada en una instancia de ECS. Sin embargo, es posible que no desee que aplicaciones no confiables accedan al servidor de metadatos para obtener el token de STS del rol de RAM asignado al nodo worker. Este tipo de aplicaciones incluye aquellas enviadas por clientes sin que le revelen el código fuente. Para garantizar la seguridad de los recursos en la nube, permitir que las aplicaciones no confiables obtengan de forma segura el token de STS necesario y minimizar los permisos a nivel de aplicación, utilice la función RAM Roles for Service Account (RRSA). La lógica subyacente de este método consiste en usar un token de STS obtenido de STS para configurar las credenciales de acceso. ACK crea y monta los archivos de token de OpenID Connect (OIDC) correspondientes para distintos pods de aplicaciones. Después, pasa la información de configuración relevante a las variables de entorno. La herramienta Credentials obtiene la información de configuración de las variables de entorno y llama a la operación AssumeRoleWithOIDC de STS para conseguir el token de STS de los roles asignados. Este método no requiere un par de AccessKey ni un token de STS, lo cual elimina los riesgos asociados con la gestión manual de estas credenciales. Para más información, consulte Use RRSA for pod-level access control.

  1. Agregue la dependencia alibabacloud_credentials.

    pip install alibabacloud_credentials
  1. Utilice el ARN de rol del IdP de OIDC como credenciales de acceso.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    import os
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        # Set the credential type to oidc_role_arn. 
        type='oidc_role_arn',
        # Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
        role_arn=os.environ.get('<RoleArn>'),
        # Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
        oidc_provider_arn=os.environ.get('<OidcProviderArn>'),
        # Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
        oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'),
        # Specify the role session name by specifying the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
        role_session_name='<RoleSessionName>',
        # (Optional) Specify limited permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
        policy='<Policy>',
        # Specify the validity period of the session.
        role_session_expiration=3600
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Usar Credentials en el contexto de Function Compute

Si la función de su aplicación se despliega y ejecuta en Function Compute, inicialice el proveedor de credenciales mediante Credentials en el contexto de Function Compute. La lógica subyacente de este método consiste en usar un token de STS obtenido de STS para configurar las credenciales de acceso. Function Compute obtiene un token de STS al asumir un rol de servicio basado en el rol configurado para la función. Luego, el token de STS se pasa a su aplicación mediante Credentials en el contexto. El token de STS tiene una validez de 36 horas y no es posible modificar su periodo de validez. Una función puede ejecutarse durante un máximo de 24 horas. No es necesario actualizar el token de STS durante la ejecución de la función, ya que permanece válido durante todo el proceso. Este método no requiere un par de AccessKey ni un token de STS, lo cual elimina los riesgos asociados con la gestión manual de estas credenciales. Para más información sobre cómo autorizar a Function Compute a acceder a OSS, consulte Use a function role to access other cloud services.

  1. Inicialice el proveedor de credenciales mediante Credentials en el contexto de Function Compute.

    # -*- coding: utf-8 -*-
    import oss2
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    def handler(event, context):
    
        class CredentialProviderWrapper(CredentialsProvider):
            def get_credentials(self):
                creds = context.credentials
                return Credentials(creds.access_key_id, creds.access_key_secret, creds.security_token)
    
        credentials_provider = CredentialProviderWrapper()
        # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
        auth = oss2.ProviderAuthV4(credentials_provider)
    
        # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
        # Specify the name of the bucket. 
        bucket_name = 'yourBucketName'
    
        # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
        region = 'cn-hangzhou'
    
        # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
        bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
        # Use the bucket object for subsequent operations.
    
        return 'success'
    

Usar CredentialsURI

Si su aplicación necesita obtener credenciales de Alibaba Cloud desde un sistema externo para implementar una gestión flexible de credenciales y acceso sin claves, utilice CredentialsURI para inicializar un proveedor de credenciales. La lógica subyacente de este método consiste en usar un token de STS obtenido de STS para configurar las credenciales de acceso. La herramienta Credentials obtiene el token de STS mediante el URI especificado para inicializar el cliente. Este método no requiere un par de AccessKey ni un token de STS, lo cual elimina los riesgos asociados con la gestión manual de estas credenciales.

Importante
  • CredentialsURI hace referencia a la dirección del servidor que genera un token de STS.

  • El servicio de backend que proporciona la respuesta del URI de credenciales debe actualizar automáticamente el token de STS. De esta manera, se garantiza que su aplicación siempre obtenga credenciales válidas.

  1. Para que la herramienta Credentials analice sintácticamente y utilice correctamente un token de STS, el URI debe cumplir los siguientes requisitos:

    • Código de estado de la respuesta: 200

    • Estructura del cuerpo de la respuesta:

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

    pip install alibabacloud_credentials
  3. Configure el URI como credencial de acceso.

    # -*- coding: utf-8 -*-
    import oss2
    from alibabacloud_credentials.client import Client
    from alibabacloud_credentials.models import Config
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    
    class CredentialProviderWrapper(CredentialsProvider):
        def __init__(self, client):
            self.client = client
    
        def get_credentials(self):
            credential = self.client.get_credential()
            access_key_id = credential.access_key_id
            access_key_secret = credential.access_key_secret
            security_token = credential.security_token
            return Credentials(access_key_id, access_key_secret, security_token)
    
    config = Config(
        type='credentials_uri',
        # Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
        credentials_uri='<CredentialsUri>',
    )
    
    cred = Client(config)
    
    credentials_provider = CredentialProviderWrapper(cred)
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

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

Si su aplicación necesita acceso a largo plazo a OSS, debe rotar manualmente el par de AccessKey para reducir los riesgos de filtración de credenciales. En este caso, utilice una clave de cliente para inicializar el proveedor de credenciales. La lógica subyacente de este método consiste en usar un par de AccessKey para acceder a los recursos de OSS. Al usar una clave de cliente, Key Management Service (KMS) rota de forma automática y periódica el par de AccessKey de un usuario de RAM administrado. Además, cambia dinámicamente el par de AccessKey estático del usuario de RAM. Esto reduce el riesgo de filtración del par de AccessKey. KMS también admite la rotación inmediata para deshabilitar rápidamente un par de AccessKey filtrado. Así se elimina la necesidad de mantener manualmente un par de AccessKey, lo cual reduce los riesgos de seguridad y la complejidad del mantenimiento. Para más información sobre cómo obtener una clave de cliente, consulte Create an application access point.

  1. Agregue las dependencias de credenciales.

    pip install aliyun-secret-manager-client
  2. Cree un archivo de configuración llamado secretsmanager.properties.

    # Set the credential type to client_key.
    credentials_type=client_key
    
    # Specify the decryption password of the client key. You can read the decryption password from environment variables 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>
    
    # Specify the path of the private key file of the client key.
    client_key_private_key_path=<your client key private key file path>
    
    # Specify the ID of the region in which you want to use KMS.
    cache_client_region_id=[{"regionId":"<regionId>"}]
  3. Pase las credenciales mediante el archivo de configuración.

    # -*- coding: utf-8 -*-
    import json
    import oss2
    from oss2 import CredentialsProvider
    from oss2.credentials import Credentials
    from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder
    
    class CredentialProviderWrapper(CredentialsProvider):
        def get_credentials(self):
            secret_cache_client = SecretManagerCacheClientBuilder.new_client()
            secret_info = secret_cache_client.get_secret_info("<secretName>")
            secret_value_json = json.loads(secret_info.secret_value)
            return Credentials(secret_value_json["AccessKeyId"], secret_value_json["AccessKeySecret"])
    
    credentials_provider = CredentialProviderWrapper()
    
    # Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
    auth = oss2.ProviderAuthV4(credentials_provider)
    
    # Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    
    # Specify the name of the bucket. 
    bucket_name = 'yourBucketName'
    
    # Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
    region = 'cn-hangzhou'
    
    # Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    # Use the bucket object for subsequent operations.
    

Uso de credenciales de acceso personalizadas

Si ninguno de los métodos anteriores cumple con sus requisitos, especifique un método personalizado para obtener las credenciales de acceso mediante la llamada a la operación CredentialsProvider. Tenga en cuenta que, si la implementación subyacente se basa en un token de STS, debe proporcionar compatibilidad con la actualización de credenciales.

# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials

class CredentialProviderWrapper(CredentialsProvider):
    def get_credentials(self):
        # TODO
        # Specify the method used to obtain the custom access credentials.

        # Return long-term access credentials (an AccessKey ID and an AccessKey secret).
        return Credentials('<access_key_id>', '<access_key_secrect>')

        # Return temporary access credentials (an AccessKey ID, an AccessKey secret, and an STS token.
        # Refresh the temporary access credentials based on the validity period. 
        # return Credentials('<access_key_id>', '<access_key_secrect>', '<token>');

credentials_provider = CredentialProviderWrapper()

# Note that ProviderAuthV4 indicates that the signature algorithm V4 is used. 
auth = oss2.ProviderAuthV4(credentials_provider)

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'

# Specify the name of the bucket. 
bucket_name = 'yourBucketName'

# Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. 
region = 'cn-hangzhou'

# Use the Auth instance to initialize the bucket. When you use the signature algorithm V4, you must specify the region parameter. Otherwise, an error is returned. 
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)

# Use the bucket object for subsequent operations.