Todos os produtos
Search
Central de documentação

:Configurar credenciais de acesso com o OSS SDK for Python 1.0

Última atualização: Jul 03, 2026

Para usar o Object Storage Service (OSS) SDK for Python e iniciar uma solicitação, configure as credenciais de acesso, que verificam sua identidade e permissões. Selecione os tipos de credenciais conforme seus requisitos de autenticação e autorização.

Notas de uso

  • Para obter a lista de regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Para saber como criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey para um usuário RAM.

  • Antes de configurar as credenciais de acesso, verifique se a versão mais recente do OSS SDK for Python está instalada. Para mais informações, consulte Instalação.

  • Certifique-se de que a versão do alibabacloud-credentials seja 0.3.5 ou posterior. Versões anteriores causam erros.

Inicialização do provedor de credenciais

O OSS oferece vários métodos para inicializar um provedor de credenciais. Escolha o método adequado conforme seus requisitos de autenticação e autorização.

Método de inicialização

Cenário

Par de AccessKey ou token STS necessário

Credencial subjacente

Período de validade da credencial

Método de rotação ou atualização da credencial

Usar o par de AccessKey de um usuário RAM

Aplicações implantadas e executadas em ambiente seguro e estável, não vulnerável a ataques externos, que precisam de acesso de longo prazo aos serviços de nuvem sem rotação frequente de credenciais.

Sim

Par de AccessKey

Longo prazo

Rotação manual

Usar credenciais de acesso temporárias fornecidas pelo STS

Aplicações implantadas e executadas em ambiente não confiável, onde você deseja gerenciar a validade das credenciais e os recursos acessíveis.

Sim

Token do Security Token Service (STS)

Temporário

Atualização manual

Usar o ARN de uma função RAM

Aplicações que exigem acesso a serviços de nuvem, como acesso entre contas.

Sim

Token STS

Temporário

Atualização automática

Usar a função RAM de uma instância ECS

Aplicações implantadas e executadas em instâncias do Elastic Compute Service (ECS), Elastic Container Instance ou nós de trabalho do Container Service for Kubernetes (ACK).

Não

Token STS

Temporário

Atualização automática

Usar a função de um OIDC IdP

Aplicações não confiáveis implantadas e executadas em nós de trabalho do ACK.

Não

Token STS

Temporário

Atualização automática

Usar o parâmetro Credentials no contexto do Function Compute

Funções das suas aplicações implantadas e executadas no Function Compute.

Não

Token STS

Temporário

Não é necessário atualizar

Usar o CredentialsURI

Aplicações que exigem credenciais de acesso de sistemas externos.

Não

Token STS

Temporário

Atualização automática

Usar um par de AccessKey com rotação automática

Aplicações implantadas em ambiente onde pares de AccessKey têm alto risco de vazamento e exigem rotação frequente de credenciais para obter acesso de longo prazo aos serviços de nuvem.

Não

Par de AccessKey

Longo prazo

Rotação automática

Usar credenciais de acesso personalizadas

Caso nenhum dos métodos anteriores atenda aos seus requisitos, use um método personalizado para obter credenciais de acesso.

Personalizado

Personalizado

Personalizado

Personalizado

Exemplos de configuração para cenários comuns

Usar o par de AccessKey de um usuário RAM

Se sua aplicação requer acesso de longo prazo ao OSS sem rotação frequente de credenciais e executa em ambiente seguro e estável, não vulnerável a ataques externos, utilize um par de AccessKey (AccessKey ID e AccessKey secret) da sua conta Alibaba Cloud ou de um usuário RAM para inicializar o provedor de credenciais. Este método exige a manutenção manual do par de AccessKey, o que aumenta a complexidade de manutenção e apresenta riscos de segurança.

Aviso
  • Uma conta Alibaba Cloud possui permissões totais sobre seus recursos, e o vazamento de seu par de AccessKey representa riscos significativos de segurança. Portanto, recomendamos o uso do par de AccessKey de um usuário RAM com as permissões mínimas necessárias para inicializar o provedor de credenciais.

  • Para saber como criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey para um usuário RAM. O par de AccessKey de um usuário RAM é exibido apenas no momento da criação. Salve-o imediatamente. Caso esqueça o par, crie um novo para rotação.

Variáveis de ambiente

  1. Configure as variáveis de ambiente para o par de AccessKey do usuário RAM.

    Linux

    1. Execute os seguintes comandos na interface de linha de comando para adicionar as configurações de variáveis de ambiente ao arquivo ~/.bashrc .

      echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc
      echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
      1. Execute o seguinte comando para aplicar as alterações.

        source ~/.bashrc
      2. Execute o seguinte comando para verificar se as variáveis de ambiente estão ativas.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. Execute o seguinte comando no terminal para verificar o tipo de shell padrão.

      echo $SHELL
      1. Realize as operações conforme o tipo de shell padrão.

        Zsh

        1. Execute os seguintes comandos para adicionar as configurações de variáveis de ambiente ao arquivo ~/.zshrc.

          echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc
          echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
        2. Execute o seguinte comando para aplicar as alterações.

          source ~/.zshrc
        3. Execute o seguinte comando para verificar se as variáveis de ambiente estão ativas.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Execute os seguintes comandos para adicionar as configurações de variáveis de ambiente ao arquivo ~/.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. Execute o seguinte comando para aplicar as alterações.

          source ~/.bash_profile
        3. Execute o seguinte comando para verificar se as variáveis de ambiente estão ativas.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

    Windows

    CMD

    1. Execute os seguintes comandos no CMD.

      setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID"
      setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
      1. Execute o seguinte comando para verificar se as variáveis de ambiente estão ativas.

        echo %OSS_ACCESS_KEY_ID%
        echo %OSS_ACCESS_KEY_SECRET%

    PowerShell

    1. Execute os seguintes comandos no 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. Execute o seguinte comando para verificar se as variáveis de ambiente estão ativas.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Para garantir que suas configurações sejam carregadas, reinicie ou atualize seus ambientes de compilação e execução, como IDE, ferramentas de linha de comando, aplicativos de desktop e serviços em segundo plano.

  3. Transmita as credenciais usando variáveis de ambiente.

    # -*- 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.

Credenciais estáticas

O exemplo a seguir mostra como codificar as credenciais de acesso de um usuário RAM diretamente no código:

Aviso

Não incorpore credenciais de acesso no código da aplicação implantado em ambiente de produção. Este método destina-se apenas a testes.

# -*- 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 credenciais de acesso temporárias fornecidas pelo STS

Caso sua aplicação precise acessar o OSS temporariamente, utilize credenciais de acesso temporárias fornecidas pelo STS, compostas por um par de AccessKey e um token STS. Este método exige a manutenção manual do token STS, o que aumenta a complexidade de manutenção e apresenta riscos de segurança. Para prolongar o acesso após a expiração do token STS existente, atualize-o manualmente.

Importante
  • Obtenha credenciais de acesso temporárias chamando a operação de API AssumeRole. Para mais informações, consulte AssumeRole.

  • Também é possível obter credenciais de acesso temporárias usando o SDK. Para mais informações, consulte Acessar o OSS usando credenciais temporárias do STS.

  • Especifique um período de validade ao gerar o token STS. Um token STS expirado não pode ser utilizado.

  • Para obter a lista de endpoints do STS, consulte Endpoints.

Variáveis de ambiente

  1. Configure as variáveis de ambiente para as credenciais de acesso temporárias.

    Mac OS X/Linux/Unix

    Aviso
    • As credenciais de acesso temporárias (AccessKey ID, AccessKey secret e token STS) fornecidas pelo STS são usadas no lugar do AccessKey ID e AccessKey secret do usuário RAM.

    • O AccessKey ID fornecido pelo STS começa com STS. Exemplo: 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
    • As credenciais de acesso temporárias (AccessKey ID, AccessKey secret e token STS) fornecidas pelo STS são usadas no lugar do par de AccessKey (AccessKey ID e AccessKey secret) do usuário RAM.

    • O AccessKey ID fornecido pelo STS começa com STS. Exemplo: 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. Transmita as informações de credenciais usando variáveis de ambiente.

    # -*- 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.

Credenciais estáticas

O exemplo a seguir mostra como codificar credenciais de acesso temporárias diretamente no código:

Aviso

Não incorpore credenciais de acesso no código da aplicação implantado em ambiente de produção. Este método destina-se apenas a testes.

# -*- 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.

Exemplos de configuração para outros cenários

Usar o ARN de uma função RAM

Para autorizar sua aplicação a acessar o OSS, por exemplo, em um cenário de acesso entre contas, utilize o Alibaba Cloud Resource Name (ARN) de uma função RAM para inicializar o provedor de credenciais. A lógica subjacente deste método utiliza um token STS obtido do STS para configurar as credenciais de acesso. A ferramenta Credentials obtém um token STS com base no ARN da função RAM e o atualiza chamando a operação AssumeRole antes que a sessão expire. Especifique uma policy para limitar as permissões concedidas à função RAM.

Importante
  • Uma conta Alibaba Cloud possui permissões totais sobre seus recursos, e o vazamento de seu par de AccessKey representa riscos significativos de segurança. Portanto, recomendamos o uso do par de AccessKey de um usuário RAM com as permissões mínimas necessárias para inicializar o provedor de credenciais.

  • Para saber como criar um par de AccessKey para um usuário RAM, consulte Criar um par de AccessKey para um usuário RAM. O par de AccessKey de um usuário RAM é exibido apenas no momento da criação. Salve-o imediatamente. Caso esqueça o par, crie um novo para rotação.

  • Crie uma função RAM chamando a operação CreateRole. O ARN da função RAM está incluído na resposta. Para mais informações, consulte CreateRole.

  1. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  2. Configure o par de AccessKey e o RAMRoleARN como credenciais de acesso.

    # -*- 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 a função RAM de uma instância ECS

Se sua aplicação for executada em uma instância ECS, uma elastic container instance ou um nó de trabalho do ACK, recomendamos usar a função RAM da instância ECS para inicializar o provedor de credenciais. A lógica subjacente deste método utiliza um token STS obtido do STS para configurar as credenciais de acesso. Anexe uma função RAM a uma instância ECS, elastic container instance ou nó de trabalho do ACK para atualizar automaticamente o token STS na instância. Este método não requer um par de AccessKey ou token STS, eliminando os riscos associados ao gerenciamento manual dessas credenciais. Crie uma função RAM chamando a operação CreateRole. O ARN está incluído na resposta. Para mais informações, consulte CreateRole.

  1. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  2. Use a função RAM para fornecer credenciais de acesso.

    # -*- 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 a função de um OIDC IdP

Após configurar a função RAM no nó de trabalho do ACK, as aplicações dentro dos pods nesse nó podem recuperar o token STS da função anexada usando o servidor de metadados, semelhante a uma aplicação implantada em uma instância ECS. No entanto, talvez você não queira que aplicações não confiáveis, como aquelas enviadas por clientes sem divulgar o código-fonte, acessem o servidor de metadados para obter o token STS da função RAM anexada ao nó de trabalho. Para garantir a segurança dos recursos de nuvem, permitir que aplicações não confiáveis obtenham com segurança o token STS necessário e minimizar as permissões no nível da aplicação, utilize o recurso RAM Roles for Service Account (RRSA). A lógica subjacente deste método utiliza um token STS obtido do STS para configurar as credenciais de acesso. O ACK cria e monta arquivos de token OpenID Connect (OIDC) correspondentes para diferentes pods de aplicação e transmite as informações de configuração relevantes para variáveis de ambiente. A ferramenta Credentials obtém as informações de configuração das variáveis de ambiente e chama a operação AssumeRoleWithOIDC do STS para obter o token STS das funções anexadas. Este método não requer um par de AccessKey ou token STS, eliminando os riscos associados ao gerenciamento manual dessas credenciais. Para mais informações, consulte Usar RRSA para controle de acesso no nível do pod.

  1. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  1. Use o ARN da função do OIDC IdP como credenciais de acesso.

    # -*- 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 no contexto do Function Compute

Se a função da sua aplicação estiver implantada e em execução no Function Compute, inicialize o provedor de credenciais usando Credentials no contexto do Function Compute. A lógica subjacente deste método utiliza um token STS obtido do STS para configurar as credenciais de acesso. O Function Compute obtém um token STS assumindo uma função de serviço com base na função configurada para a função da aplicação. Em seguida, o token STS é transmitido à sua aplicação usando Credentials no contexto. O token STS tem validade de 36 horas e seu período de validade não pode ser alterado. Uma função pode ser executada por até 24 horas. Não é necessário atualizar o token STS durante a execução da função, pois ele permanece válido durante todo o processo. Este método não requer um par de AccessKey ou token STS, eliminando os riscos associados ao gerenciamento manual dessas credenciais. Para mais informações sobre como autorizar o Function Compute a acessar o OSS, consulte Usar uma função de função para acessar outros serviços de nuvem.

  1. Inicialize o provedor de credenciais usando Credentials no contexto do 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 o CredentialsURI

Caso sua aplicação precise obter credenciais da Alibaba Cloud de um sistema externo para implementar gerenciamento flexível de credenciais e acesso sem chave, utilize o CredentialsURI para inicializar um provedor de credenciais. A lógica subjacente deste método utiliza um token STS obtido do STS para configurar as credenciais de acesso. A ferramenta Credentials obtém o token STS usando o URI especificado para inicializar o cliente. Este método não requer um par de AccessKey ou token STS, eliminando os riscos associados ao gerenciamento manual dessas credenciais.

Importante
  • O CredentialsURI refere-se ao endereço do servidor que gera um token STS.

  • O serviço de back-end que fornece a resposta do URI de credenciais deve atualizar automaticamente o token STS para garantir que sua aplicação sempre obtenha credenciais válidas.

  1. Para que a ferramenta Credentials analise e use corretamente um token STS, o URI deve atender aos seguintes requisitos:

    • Código de status da resposta: 200

    • Estrutura do corpo da resposta:

      {
          "Code": "Success",
          "AccessKeySecret": "AccessKeySecret",
          "AccessKeyId": "AccessKeyId",
          "Expiration": "2021-09-26T03:46:38Z",
          "SecurityToken": "SecurityToken"
      }
  2. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  3. Configure o URI como credencial de acesso.

    # -*- 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 um par de AccessKey com rotação automática

Se sua aplicação precisar de acesso de longo prazo ao OSS, realize a rotação manual do par de AccessKey para reduzir os riscos de vazamento de credenciais. Nesse caso, utilize uma chave de cliente para inicializar o provedor de credenciais. A lógica subjacente deste método utiliza um par de AccessKey para acessar recursos do OSS. Ao usar uma chave de cliente, o Key Management Service (KMS) pode rotacionar automática e regularmente o par de AccessKey de um usuário RAM gerenciado e alterar dinamicamente o par de AccessKey estático desse usuário. Isso reduz o risco de vazamentos do par de AccessKey. O KMS também suporta rotação imediata para desabilitar rapidamente um par de AccessKey vazado. Isso elimina a necessidade de manter manualmente um par de AccessKey e reduz os riscos de segurança e a complexidade de manutenção. Para mais informações sobre como obter uma chave de cliente, consulte Criar um ponto de acesso de aplicação.

  1. Adicione as dependências de credenciais.

    pip install aliyun-secret-manager-client
  2. Crie um arquivo de configuração chamado 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. Transmita as credenciais usando o arquivo de configuração.

    # -*- 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.
    

Usar credenciais de acesso personalizadas

Caso nenhum dos métodos anteriores atenda aos seus requisitos, especifique um método personalizado para obter credenciais de acesso chamando a operação CredentialsProvider. Se a implementação subjacente for baseada em um token STS, será necessário fornecer suporte para atualização de credenciais.

# -*- 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.