Todos os produtos
Search
Central de documentação

:Configure credenciais de acesso usando o OSS SDK for Python 1.0

Última atualização: Sep 25, 2026

Para usar o SDK do Object Storage Service (OSS) para Python e iniciar uma requisição, configure as credenciais de acesso, usadas para verificar sua identidade e permissões de acesso. Selecione diferentes tipos de credenciais de acesso de acordo com os requisitos de autenticação e autorização.

Notas de uso

  • Para ver a lista de regiões e endpoints do OSS, consulte Regions and endpoints.

  • Para saber como criar um par de AccessKey para um usuário RAM, consulte Create an AccessKey pair for a RAM user.

  • Antes de configurar as credenciais de acesso, instale a versão mais recente do OSS SDK for Python. Para mais informações, consulte Installation.

  • 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 suporte a vários métodos de inicialização de provedor de credenciais. Selecione o método adequado de acordo com 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

Use the AccessKey pair of a RAM user

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

Sim

Par de AccessKey

Longo prazo

Rotação manual

Use temporary access credentials provided by STS

Aplicações implantadas e executadas em ambiente não confiável, nas quais você deseja gerencie a validade da credencial e os recursos acessíveis.

Sim

Token do Security Token Service (STS)

Temporário

Atualização manual

Use the ARN of a RAM role

Aplicações que exigem acesso a service de cloud, como o acesso entre contas.

Sim

Token STS

Temporário

Atualização automática

Use the RAM role of an ECS instance

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

Use the role of an 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

Use the Credentials parameter in the context of Function Compute

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

Não

Token STS

Temporário

Não é necessário atualizar

Use the CredentialsURI

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

Não

Token STS

Temporário

Atualização automática

Use an AccessKey pair that automatically rotates

Aplicações implantadas em ambiente com alto risco de vazamento de pares de AccessKey e que exigem rotação frequente de credenciais de acesso para obter acesso de longo prazo aos service de cloud.

Não

Par de AccessKey

Longo prazo

Rotação automática

Use custom access credentials

Cenários em que nenhum dos métodos anteriores atende aos requisitos, permitindo o uso de um método personalizado para obter credenciais de acesso.

Personalizado

Personalizado

Personalizado

Personalizado

Exemplos de configuração para cenários comuns

Use o par de AccessKey de um usuário RAM

Suponha que sua aplicação exija acesso de longo prazo ao OSS sem rotação frequente de credenciais e seja executada em um ambiente seguro e estável, não vulnerável a ataques externos. Nesse caso, use um par de AccessKey (AccessKey ID e AccessKey secret) da sua conta Alibaba Cloud ou de um usuário RAM para inicializar um provedor de credenciais. Note que este método exige a manutenção manual do par de AccessKey, o que gera riscos de segurança e aumenta a complexidade de manutenção.

Aviso
  • Uma conta Alibaba Cloud tem permissões totais sobre seus recursos, e o vazamento do seu par de AccessKey representa um risco significativo à 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 Create an AccessKey pair for a RAM user. O par de AccessKey de um usuário RAM é exibido apenas no momento da criação do usuário. Salve o par de AccessKey imediatamente. Caso o esqueça, crie um novo par para rotação.

Variáveis de ambiente

  1. Para o par de AccessKey do usuário RAM, defina as variáveis de ambiente.

    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. Aplique as alterações executando o seguinte comando.

        source ~/.bashrc
      2. Verifique se as variáveis de ambiente estão ativas com o comando abaixo.

        echo $OSS_ACCESS_KEY_ID
        echo $OSS_ACCESS_KEY_SECRET

    macOS

    1. No terminal, execute o comando abaixo para verificar o tipo de shell padrão.

      echo $SHELL
      1. Execute as operações com base no tipo de shell padrão.

        Zsh

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

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

          source ~/.zshrc
        3. Verifique se as variáveis de ambiente estão ativas executando o comando abaixo.

          echo $OSS_ACCESS_KEY_ID
          echo $OSS_ACCESS_KEY_SECRET

        Bash

        1. Para adicionar as configurações de variáveis de ambiente ao arquivo ~/.bash_profile, execute os seguintes comandos.

          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. Aplique as alterações executando o seguinte comando.

          source ~/.bash_profile
        3. Verifique se as variáveis de ambiente estão ativas com o comando abaixo.

          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. Verifique se as variáveis de ambiente estão ativas executando o comando abaixo.

        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. Verifique se as variáveis de ambiente estão ativas com o seguinte comando.

        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User)
        [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
  2. Para garantir o carregamento das suas configurações, reinicie ou atualize seus ambientes de compilação e execução, como a IDE, a ferramenta de linha de comando, as aplicações de desktop e os service em segundo plano.

  3. Forneça as credenciais por meio de 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

No exemplo a seguir, insira 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 implantada 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.

Use credenciais de acesso temporárias fornecidas pelo STS

Se sua aplicação precisar acessar o OSS temporariamente, use credenciais de acesso temporárias fornecidas pelo STS, compostas por um par de AccessKey e um token STS. Note que este método exige a manutenção manual do token STS, o que gera riscos de segurança e aumenta a complexidade de manutenção. Para prolongar o acesso após a expiração do token STS atual, atualize o token manualmente.

Importante
  • Obtenha credenciais de acesso temporárias chamando a operação da 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 Access OSS by using STS temporary credentials.

  • Especifique um período de validade para o token STS ao gerá-lo. Um token STS expirado não é válido.

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

Variáveis de ambiente

  1. Para as credenciais de acesso temporárias, defina as variáveis de ambiente.

    Mac OS X/Linux/Unix

    Aviso
    • Note que as credenciais de acesso temporárias (AccessKey ID, AccessKey secret e token STS) fornecidas pelo STS substituem o AccessKey ID e o 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
    • Note que as credenciais de acesso temporárias (AccessKey ID, AccessKey secret e token STS) fornecidas pelo STS substituem o 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. Forneça as informações de credenciais por meio de 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

No exemplo a seguir, insira as credenciais de acesso temporárias diretamente no código:

Aviso

Não incorpore credenciais de acesso no código da aplicação implantada 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

Use o ARN de uma função RAM

Para autorizar sua aplicação a acessar o OSS, como em um cenário de acesso entre contas, use o Alibaba Cloud Resource Name (ARN) de uma função RAM para inicializar um provedor de credenciais. A lógica subjacente deste método consiste em usar 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 tem permissões totais sobre seus recursos, e o vazamento do seu par de AccessKey representa um risco significativo à 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 Create an AccessKey pair for a RAM user. O par de AccessKey de um usuário RAM é exibido apenas no momento da criação do usuário. Salve o par de AccessKey imediatamente. Caso o esqueça, crie um novo par 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.
    

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

Caso sua aplicação seja executada em uma instância ECS, uma instância de contêiner elástico ou um nó de trabalho do ACK, recomendamos o uso da função RAM da instância ECS para inicializar um provedor de credenciais. A lógica subjacente deste método consiste em usar um token STS obtido do STS para configurar as credenciais de acesso. Anexe uma função RAM a uma instância ECS, uma instância de contêiner elástico ou um 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, o que elimina 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.
    

Use a função de um IdP OIDC

Após a configuração da função RAM no nó de trabalho do ACK, as aplicações nos pods desse nó podem recuperar o token STS da função anexada por meio do servidor de metadados, de forma 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 as enviadas por clientes sem a divulgação do código, 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 cloud, permitir que aplicações não confiáveis obtenham o token STS necessário com segurança e minimizar as permissões no nível da aplicação, use o recurso RAM Roles for Service Account (RRSA). A lógica subjacente deste método consiste em usar um token STS obtido do STS para configurar as credenciais de acesso. O ACK cria e monta os 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, o que elimina os riscos associados ao gerenciamento manual dessas credenciais. Para mais informações, consulte Use RRSA for pod-level access control.

  1. Adicione a dependência alibabacloud_credentials.

    pip install alibabacloud_credentials
  1. Use o ARN da função do IdP OIDC 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.
    

Use Credentials no contexto do Function Compute

Caso a função da sua aplicação seja implantada e executada no Function Compute, inicialize o provedor de credenciais usando Credentials no contexto do Function Compute. A lógica subjacente deste método consiste em usar 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 (role) configurada para a função (function). Em seguida, o sistema transmite o token STS para sua aplicação por meio do Credentials no contexto. O token STS tem validade de 36 horas, período que 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 por toda a execução. Este método não requer um par de AccessKey ou token STS, o que elimina os riscos associados ao gerenciamento manual dessas credenciais. Para saber como autorizar o Function Compute a acessar o OSS, consulte Use a function role to access other cloud services.

  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'
    

Use o CredentialsURI

Caso sua aplicação precise obter credenciais da Alibaba Cloud de um sistema externo para implementar um gerenciamento flexível de credenciais e acesso sem chaves, use o CredentialsURI para inicializar um provedor de credenciais. A lógica subjacente deste método consiste em usar um token STS obtido do STS para configurar as credenciais de acesso. A ferramenta Credentials obtém o token STS por meio do URI especificado para inicializar o cliente. Este método não requer um par de AccessKey ou token STS, o que elimina 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 backend 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 a 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.
    

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

Caso sua aplicação precise de acesso de longo prazo ao OSS, será necessário rotacionar manualmente o par de AccessKey para reduzir os riscos de vazamento de credenciais. Nesse caso, use uma chave de cliente para inicializar o provedor de credenciais. A lógica subjacente deste método consiste em usar um par de AccessKey para acessar os recursos do OSS. Com o uso de 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, alterando dinamicamente o par de AccessKey estático do usuário RAM. Essa abordagem reduz o risco de vazamentos do par de AccessKey. O KMS também oferece suporte à rotação imediata para desativar rapidamente um par de AccessKey vazado. Assim, elimina-se a necessidade de manter manualmente um par de AccessKey, reduzindo os riscos de segurança e a complexidade de manutenção. Para saber como obter uma chave de cliente, consulte Create an application access point.

  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. Forneça as credenciais por meio do 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.
    

Use 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. Note que, se a implementação subjacente for baseada em um token STS, será necessário fornecer suporte para a 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.