Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Gerenciamento de credenciais de acesso

Última atualização: Jun 28, 2026

O Alibaba Cloud SDK usa a ferramenta Credentials para gerenciar centralmente credenciais, como AccessKey e STS Token. Este tópico descreve os tipos de credenciais compatíveis e seus métodos de configuração.

Pré-requisitos

  • .NET Framework 4.5 ou superior.

  • .NET Standard 2.0 ou superior.

  • C# 4,0 ou superior.

  • Alibaba Cloud SDK for .NET V2.0 ou superior.

Instalação da ferramenta de credenciais

Se você já instalou o Alibaba Cloud Credentials for .NET, ignore esta etapa. Use a versão mais recente do pacote de credenciais para garantir compatibilidade com todos os tipos de credenciais. Para obter informações sobre todas as versões lançadas, consulte ChangeLog.md.

Instale o Alibaba Cloud Credentials for .NET de uma das seguintes formas:

  • Instale o pacote com a CLI do .NET.

    dotnet add package Aliyun.Credentials
  • Instale o pacote com o gerenciador de pacotes NuGet.

    1. Clique com o botão direito no projeto em Solution Explorer e selecione Manage NuGet Packages.

    2. No NuGet Package Manager, clique em na guia Browse e insira Aliyun.Credentials.

    3. Na lista, selecione o pacote oficial cujo campo Authors seja Alibaba Cloud e clique em Install.

Após concluir a instalação, execute o comando a seguir. A saída listará o Aliyun.Credentials e seu número de versão:

dotnet list package

Parâmetros da ferramenta de credenciais

Os parâmetros de configuração da ferramenta de credenciais são definidos em Aliyun.Credentials.Models.Config. O parâmetro obrigatório type especifica o tipo de credencial. Após selecionar um tipo de credencial, configure os parâmetros correspondentes. A tabela a seguir detalha os valores válidos para type e os parâmetros compatíveis com cada tipo de credencial. Na tabela, √ indica um parâmetro obrigatório, - indica um parâmetro opcional e × indica um parâmetro não compatível.

Nota

Use apenas os tipos de credenciais e parâmetros listados na tabela a seguir.

Type

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

AccessKeyId: O ID da chave de acesso.

√

√

√

×

×

×

×

AccessKeySecret: O segredo da chave de acesso.

√

√

√

×

×

×

×

SecurityToken: O token de segurança.

×

√

-

×

×

×

×

RoleArn: O ARN da função RAM.

×

×

√

×

√

×

×

RoleSessionName: O nome da sessão personalizada. O formato padrão é credentials-csharp-<timestamp>.

×

×

-

×

-

×

×

RoleName: O nome da função RAM.

×

×

×

-

×

×

×

DisableIMDSv1: Especifica se o IMDSv1 deve ser desativado para impor o modo de reforço de segurança (IMDSv2). O valor padrão é false.

×

×

×

-

×

×

×

BearerToken: O token bearer.

×

×

×

×

×

×

√

Policy: Uma política personalizada.

×

×

-

×

-

×

×

RoleSessionExpiration: O tempo limite da sessão, em segundos. O valor padrão é 3600.

×

×

-

×

-

×

×

OidcProviderArn: O ARN do provedor de identidade OIDC.

×

×

×

×

√

×

×

OidcTokenFilePath: O caminho do arquivo para o token OIDC.

×

×

×

×

√

×

×

ExternalId: Um ID externo usado para evitar o problema de "confused deputy". Para mais informações, consulte Usar um ID externo para evitar o problema de confused deputy.

×

×

-

×

×

×

×

CredentialsURI: O URI da credencial.

×

×

×

×

×

√

×

STSEndpoint: O endpoint do STS. Há compatibilidade com endpoints de VPC e públicos. Para obter uma lista de valores válidos, consulte Endpoints. O valor padrão é sts.aliyuncs.com.

×

×

-

×

-

×

×

Timeout: O tempo limite de leitura para solicitações HTTP, em milissegundos. O valor padrão é 5000.

×

×

-

-

-

-

×

ConnectTimeout: O tempo limite de conexão para solicitações HTTP, em milissegundos. O valor padrão é 10000.

×

×

-

-

-

-

×

Inicialização do cliente de credenciais

A seção anterior descreveu os tipos de credenciais e os parâmetros de configuração compatíveis com a ferramenta Credentials. As seções a seguir fornecem exemplos de código que demonstram como usar a ferramenta. Selecione o método mais adequado ao seu cenário.

Importante
  • Codificar rigidamente um AccessKey no projeto gera riscos de segurança. Permissões de repositório mal gerenciadas podem expor todos os recursos da sua conta. Armazene o AccessKey em variáveis de ambiente ou arquivos de configuração.

  • Adote o padrão singleton com a ferramenta Credentials. Esse padrão permite que o cache interno de credenciais da ferramenta evite limitações de taxa devido a chamadas frequentes de API e previne desperdício de recursos causado pela criação de múltiplas instâncias. Para mais informações, consulte Atualização automática de credenciais de sessão.

Método 1: Cadeia de provedores de credenciais padrão

Ao inicializar um cliente Credentials sem parâmetros, a ferramenta Credentials usa a cadeia de provedores de credenciais padrão. Para entender como o SDK carrega as credenciais padrão, consulte Cadeia de provedores de credenciais padrão.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Pass no parameters, or pass null.
            var credential = new Aliyun.Credentials.Client();
            // var credential = new Aliyun.Credentials.Client(null);
        }
    }
}

Exemplo de chamada de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Instale o ECS SDK antes de executar o código.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the Credentials client by using the default credential provider chain.
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(null);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the service endpoint. This example uses the China (Beijing) region.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request object for the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and get the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 2: AccessKey

A ferramenta Credentials usa o AccessKey fornecido por você como credencial de acesso.

Aviso

Uma conta Alibaba Cloud (conta raiz) possui permissões totais sobre todos os seus recursos; portanto, um AK exposto representa um risco significativo de segurança. Não use o AK de uma conta raiz.

Use o AK de um usuário RAM com permissões de privilégio mínimo.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "access_key",                    
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),          
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")   
            };
            var akCredential = new Aliyun.Credentials.Client(config);
            string accessKeyId = akCredential.GetAccessKeyId();
            string accessSecret = akCredential.GetAccessKeySecret();
            string credentialType = akCredential.GetType();
        }
    }
}

Exemplo de API

Este exemplo chama a operação DescribeRegions do ECS. Antes de executar o código, instale o ECS SDK.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Use an AccessKey pair to initialize the Credentials client.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "access_key",
                // Obtain the AccessKey ID from an environment variable.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey Secret from an environment variable.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Specify the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 3: Uso de token STS

A ferramenta Credentials usa o token STS estático fornecido por você como credencial de acesso.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "sts", 
                // Get the AccessKey ID from an environment variable.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Get the AccessKey Secret from an environment variable.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), 
                // Get the security token from an environment variable.
              	SecurityToken = Environment.GetEnvironmentVariable("<ALIBABA_CLOUD_SECURITY_TOKEN>")
            };
            var stsCredential = new Aliyun.Credentials.Client(config);
            string accessKeyId = stsCredential.GetAccessKeyId();
            string accessSecret = stsCredential.GetAccessKeySecret();
            string credentialType = stsCredential.GetType();
            string securityToken = stsCredential.GetSecurityToken();
        }
    }

Exemplo de chamada de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Antes de executar o código, instale o ECS SDK for .NET e o STS SDK for .NET.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the Credentials client with STS credentials.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "sts", 
                // Get the AccessKey ID from an environment variable.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Get the AccessKey Secret from an environment variable.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), 
                // Get the temporary SecurityToken from an environment variable.
              	SecurityToken = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN")
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = ecsClient.DescribeRegionsWithOptions(describeRegionsRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 4: Chave de acesso e ARN de função RAM

Este método usa internamente um token STS. Ao especificar o ARN (Alibaba Cloud Resource Name) de uma função RAM, a ferramenta de credenciais obtém um token STS do serviço STS. Também é possível usar o parâmetro Policy para aplicar um conjunto de permissões mais restrito à função RAM.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "ram_role_arn",                  
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
              	// The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",  
              	// The role session name. You can also set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>", 
            };
            var arnCredential = new Aliyun.Credentials.Client(config);
            string accessKeyId = arnCredential.GetAccessKeyId();
            string accessSecret = arnCredential.GetAccessKeySecret();
            string credentialType = arnCredential.GetType();
            string securityToken = arnCredential.GetSecurityToken();
        }
    }
}

Chamada de API

Este exemplo demonstra como chamar a operação DescribeRegions no ECS. É necessário instalar o ECS SDK antes de executar o código.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the Credentials client with an AccessKey pair and a RAM role ARN.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "ram_role_arn",
                // Specify your AccessKey ID.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Specify your AccessKey Secret.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // The role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>",
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Set the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation to get the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 5: Função RAM de instância ECS

É possível anexar uma função RAM de instância a instâncias ECS e ECI, permitindo que as aplicações nessas instâncias usem a ferramenta Credentials para recuperar automaticamente o token STS da função e inicializar um cliente de credenciais.

Por padrão, a ferramenta Credentials usa o modo de reforço de segurança (IMDSv2) para acessar o servidor de metadados do ECS. Caso ocorra um erro, a ferramenta reverte para o modo normal a fim de recuperar a credencial de acesso. Configure esse comportamento de reversão definindo o parâmetro disableIMDSv1 ou a variável de ambiente ALIBABA_CLOUD_IMDSV1_DISABLE:

  • Se o valor for false (padrão), a ferramenta continua a recuperar a credencial de acesso no modo normal.

  • Se o valor for true, a ferramenta usa apenas o modo de reforço de segurança. Se a recuperação falhar, uma exceção será lançada.

A compatibilidade com o IMDSv2 depende da configuração do servidor.

Também é possível definir a variável de ambiente ALIBABA_CLOUD_ECS_METADATA_DISABLED=true para desativar a recuperação de credenciais dos metadados da instância ECS.

Nota
using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new Config()
            {
                Type = "ecs_ram_role",
              	// Optional. The ECS RAM role name. Specify this parameter to reduce the number of requests. If omitted, the system automatically retrieves the role name. You can also set the role name by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
                RoleName = "<RoleName>" 
            };
            // Optional. Default: false. Set to true to enforce security hardening mode. If false, the system first attempts to retrieve the access credentials in security hardening mode and falls back to normal mode (IMDSv1) on failure.
            // config.DisableIMDSv1 = true;
            var ecsCredential = new Aliyun.Credentials.Client(config);
            string accessKeyId = ecsCredential.GetAccessKeyId();
            string accessSecret = ecsCredential.GetAccessKeySecret();
            string credentialType = ecsCredential.GetType();
            string securityToken = ecsCredential.GetSecurityToken();
        }
    }
}

Exemplo de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Antes de executar o código, instale o ECS SDK for .NET.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client using the RAM role of an ECS instance.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "ecs_ram_role",
              	// Optional. The name of the RAM role for the ECS instance. If you omit this parameter, the system automatically retrieves the role name. Specifying this parameter reduces requests. You can also set the role name with the ALIBABA_CLOUD_ECS_METADATA environment variable.
                RoleName = "<RoleName>"
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize the DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 6: Uso de OIDCRoleArn

Se você usar OIDC para autenticação e tiver criado uma função RAM para um provedor de identidade OIDC, forneça o ARN do provedor OIDC, o caminho do arquivo de token OIDC e o ARN da função RAM à ferramenta Credentials. A ferramenta então chama automaticamente a API AssumeRoleWithOIDC para obter um token STS para a função RAM, usado como credencial de acesso. Credenciais obtidas dessa forma oferecem compatibilidade com atualização automática. Para mais informações, consulte Atualização automática de credenciais de sessão. Por exemplo, se sua aplicação for executada em um cluster Container Service for Kubernetes (ACK) com RRSA ativado, a ferramenta Credentials poderá ler a configuração OIDC das variáveis de ambiente do pod e chamar a API AssumeRoleWithOIDC para obter um token STS. Em seguida, use esse token STS para acessar os serviços da Alibaba Cloud.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "oidc_role_arn",
                // The ARN of the RAM role to assume. Set with the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // The ARN of the OIDC IdP. Set with the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                OIDCProviderArn = "<OidcProviderArn>",
                // The path of the OIDC token file. Set with the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                OIDCTokenFilePath = "<OidcTokenFilePath>",
                // The role session name. Set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>",
                // Optional. A custom policy that limits the permissions for the role session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                Policy = "<Policy>",
                RoleSessionExpiration = 3600
            };
            var ecsCredential = new Aliyun.Credentials.Client(config);
        }
    }
}

Exemplo de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Para executar este exemplo, instale o ECS SDK for .NET.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client with an OIDC role ARN.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The type of credential.
                Type = "oidc_role_arn",
                // The ARN of the RAM role to assume. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // The ARN of the OIDC provider. You can set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                OIDCProviderArn = "<OidcProviderArn>",
                // The path to the OIDC token file. You can set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                OIDCTokenFilePath = "<OidcTokenFilePath>",
                // The name for the role session. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>",
                // Optional. Specify a more restrictive policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                Policy = "<Policy>",
                RoleSessionExpiration = 3600
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the service endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 7: URI de credencial

É possível encapsular o Security Token Service (STS) atrás de um URI de serviço, permitindo que serviços externos obtenham um token STS sem expor informações sensíveis, como AKs. A ferramenta Credentials pode então usar esse URI para buscar um token STS e utilizá-lo como credencial de acesso. Credenciais obtidas dessa forma oferecem compatibilidade com atualização automática. Para mais informações, consulte Atualização automática de credenciais de sessão.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "credentials_uri",
              	// Specifies the URI for fetching the credential, e.g., http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
                CredentialsURI = "<CredentialsURI>"     
            };
        }
    }
}

Exemplo de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Instale o ECS SDK for .NET antes de executar o código.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client using a URI.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "credentials_uri",
              	// The URI used to retrieve credentials, in `http://local_or_remote_uri/` format. The SDK also reads the URI from the `ALIBABA_CLOUD_CREDENTIALS_URI` environment variable.
                CredentialsURI = "<CredentialsURI>" 
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the service endpoint. This example uses the China (Beijing) region.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configuration.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Calls the DescribeRegions operation and stores the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeRegionsRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Método 8: Token Bearer

Apenas o Cloud Call Center (CCC) oferece compatibilidade com a inicialização de credenciais com um token bearer.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "bearer",
                // Enter your Bearer Token.
                BearerToken = "<BearerToken>"      
            };
            var bearerCredential = new Aliyun.Credentials.Client(config);
            string bearerToken = bearerCredential.GetBearerToken();
            string credentialType = bearerCredential.GetType();
        }
    }
}

Exemplo de API

Este exemplo demonstra como chamar a operação GetInstance do Cloud Call Center. É necessário instalar o CCC SDK antes de executar o código.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the credential client with a bearer token.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "bearer",
                // Specify your bearer token.
                BearerToken = "<BearerToken>"
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config cccConfig = new AlibabaCloud.OpenApiClient.Models.Config()
            {
                // Configure the endpoint.
                Endpoint = "ccc.cn-shanghai.aliyuncs.com",
                // Set the credential object for authentication.
                Credential = credentialClient
            };
            // Initialize the CCC client.
            AlibabaCloud.SDK.CCC20200701.Client cccClient = new AlibabaCloud.SDK.CCC20200701.Client(cccConfig);
            // Initialize a GetInstance request.
            AlibabaCloud.SDK.CCC20200701.Models.GetInstanceRequest getInstanceRequest = new AlibabaCloud.SDK.CCC20200701.Models.GetInstanceRequest
            {
                InstanceId = "ccc-test",
            };
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the GetInstance operation.
            AlibabaCloud.SDK.CCC20200701.Models.GetInstanceResponse response = cccClient.GetInstanceWithOptions(getInstanceRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Cadeia de provedores de credenciais padrão

Quando sua aplicação usa credenciais diferentes para os ambientes de desenvolvimento e produção, os desenvolvedores geralmente escrevem código condicional para carregar o conjunto correto para cada ambiente. A cadeia de provedores de credenciais padrão permite usar o mesmo código e gerenciar credenciais para diferentes ambientes por meio de configuração externa. Ao inicializar um cliente de credenciais chamando new Client(config) sem parâmetros ou com null, o Alibaba Cloud SDK tenta encontrar credenciais na seguinte ordem.

1. Uso de variáveis de ambiente

Se nenhuma credencial for encontrada nas propriedades do sistema, a cadeia de provedores verificará as variáveis de ambiente.

  • Se ALIBABA_CLOUD_ACCESS_KEY_ID e ALIBABA_CLOUD_ACCESS_KEY_SECRET estiverem presentes e não vazias, a cadeia de provedores as usará como credencial padrão.

  • Se ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET e ALIBABA_CLOUD_SECURITY_TOKEN também estiverem definidas, a cadeia de provedores usará um token STS como credencial padrão.

2. Uso de uma função RAM OIDC

Caso nenhuma credencial tenha sido encontrada, a cadeia de provedores verifica as seguintes variáveis de ambiente relacionadas a uma função RAM OIDC:

  • ALIBABA_CLOUD_ROLE_ARN: O ARN da função RAM.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: O ARN do provedor OIDC.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: O caminho do arquivo do token OIDC.

Se todas as três variáveis de ambiente estiverem presentes e não vazias, a cadeia de provedores usa esses valores para chamar a API AssumeRoleWithOIDC do Security Token Service (STS) e obter um token STS.

3. Uso de config.json

Se nenhuma credencial tiver sido encontrada, a cadeia de provedores tentará carregar o arquivo de credenciais compartilhadas, config.json, de seu local padrão e usará a credencial especificada no arquivo.

  • Linux/macOS: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

Para configurar uma credencial dessa maneira, use a Alibaba Cloud CLI ou crie manualmente um arquivo config.json no caminho apropriado. O exemplo a seguir mostra o formato do conteúdo:

{
  "current": "<PROFILE_NAME>",
  "profiles": [
    {
      "name": "<PROFILE_NAME>",
      "mode": "AK",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
    },
    {
      "name": "<PROFILE_NAME1>",
      "mode": "StsToken",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "sts_token": "<SECURITY_TOKEN>"
    },
    {
      "name":"<PROFILE_NAME2>",
      "mode":"RamRoleArn",
      "access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME3>",
      "mode":"EcsRamRole",
      "ram_role_name":"<RAM_ROLE_ARN>"
    },
    {
      "name":"<PROFILE_NAME4>",
      "mode":"OIDC",
      "oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
      "oidc_token_file":"<OIDC_TOKEN_FILE>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    },
    {
      "name":"<PROFILE_NAME5>",
      "mode":"ChainableRamRoleArn",
      "source_profile":"<PROFILE_NAME>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    }
  ]
}

Parâmetro

Descrição

current

Especifique o nome da credencial para recuperar a configuração de credencial correspondente. O nome da credencial é o valor do parâmetro name em profiles. Por padrão, o sistema prioriza o nome da credencial especificado pela variável de ambiente ALIBABA_CLOUD_PROFILE. Se essa variável de ambiente não estiver configurada, o sistema usa o nome da credencial especificado por current.

profiles

Contém uma coleção de configurações de credenciais. O parâmetro mode especifica o tipo de credencial:

  • AK: Usa o AccessKey de um usuário RAM como credencial.

  • StsToken: Usa um token STS como credencial.

  • RamRoleArn: Assume uma função RAM usando as credenciais de um usuário RAM para obter uma credencial temporária.

  • EcsRamRole: Obtém uma credencial dos metadados da instância.

  • OIDC: Obtém uma credencial usando um ARN de provedor OIDC, um token OIDC e um ARN de função RAM.

  • ChainableRamRoleArn: Usa encadeamento de funções para obter uma nova credencial, utilizando uma credencial inicial de profiles especificada pelo parâmetro source_profile.

4. Função RAM de instância ECS

Se sua aplicação for executada em uma instância Elastic Compute Service (ECS) ou Elastic Container Instance (ECI) com uma função RAM atribuída, a ferramenta Credentials recupera um token STS dos metadados da instância para usar como credencial de acesso. Ao acessar os metadados da instância, a ferramenta primeiro recupera o nome da função RAM atribuída à instância. Especifique o nome da função RAM usando o parâmetro roleName ou a variável de ambiente ALIBABA_CLOUD_ECS_METADATA para reduzir o tempo de recuperação e melhorar a eficiência. Credenciais obtidas dessa forma oferecem compatibilidade com atualização automática. Para mais informações, consulte Atualização automática de credenciais de sessão.

  • Se definido como false (padrão), a ferramenta reverte para o modo normal para recuperar a credencial.

  • Se definido como true, a ferramenta usa apenas o modo seguro e lança uma exceção se o acesso falhar.

A compatibilidade do servidor com o IMDSv2 depende de sua configuração.

Para desativar o acesso a credenciais via metadados da instância, defina a variável de ambiente ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Nota

5. URI da ferramenta Credentials

Se nenhuma credencial for encontrada, a cadeia de provedores verifica a variável de ambiente ALIBABA_CLOUD_CREDENTIALS_URI. Se essa variável estiver definida e apontar para um URI válido, a cadeia acessará o URI para recuperar um token STS.

Atualização automática de credenciais de sessão

Tipos de credenciais de sessão, como ram_role_arn, ecs_ram_role, oidc_role_arn e credentials_uri, oferecem compatibilidade com atualização automática por meio de um mecanismo integrado no provedor de credenciais. Quando um cliente de credenciais recupera uma credencial pela primeira vez, o provedor a armazena em cache. Nas operações subsequentes, a mesma instância do cliente recupera automaticamente a credencial desse cache. Se a credencial em cache tiver expirado, a instância do cliente busca uma nova e atualiza o cache adequadamente.

Nota

Para credenciais ecs_ram_role, o provedor de credenciais as atualiza proativamente 15 minutos antes da expiração.

O exemplo a seguir usa o padrão singleton para criar um cliente de credenciais. Ele demonstra o mecanismo de atualização buscando uma credencial em intervalos de tempo diferentes e chamando uma operação OpenAPI para verificar se a credencial é utilizável.

using System;
using System.Threading.Tasks;
using Aliyun.Credentials.Models;
using AlibabaCloud.SDK.Ecs20140526;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.TeaUtil.Models;
namespace Example
{
    /// <summary>
    /// The Credential class manages the Alibaba Cloud credential instance by using the static singleton pattern.
    /// </summary>
    public static class Credential
    {
        private static readonly Lazy<Aliyun.Credentials.Client> _instance = new(() =>
        {
            try
            {
                var config = new Aliyun.Credentials.Models.Config
                {
                    Type = "ram_role_arn",
                    AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                    AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                    RoleArn = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ROLE_ARN"),
                    RoleSessionName = "RamRoleArnTest",
                    RoleSessionExpiration = 3600
                };
                return new Aliyun.Credentials.Client(config);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Credential initialization failed: " + ex.Message, ex);
            }
        });
        public static Aliyun.Credentials.Client Instance => _instance.Value;
    }
    /// <summary>
    /// The EcsClient class manages the ECS client instance by using the static singleton pattern.
    /// You must set the endpoint and credential by using Initialize.
    /// </summary>
    public static class EcsClient
    {
        private static string _endpoint = string.Empty; // Explicitly initialize. The value cannot be null.
        private static Aliyun.Credentials.Client _credential = null!; // Explicitly initialize. The value cannot be null.
        private static readonly Lazy<AlibabaCloud.SDK.Ecs20140526.Client> _instance = new(() =>
        {
            if (string.IsNullOrEmpty(_endpoint))
            {
                throw new InvalidOperationException("Endpoint must be set before initializing the ECS client.");
            }
            if (_credential == null)
            {
                throw new InvalidOperationException("Credential must be set before initializing the ECS client.");
            }
            try
            {
                var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
                {
                    Endpoint = _endpoint,
                    Credential = _credential
                };
                return new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("ECS client initialization failed: " + ex.Message, ex);
            }
        });
        public static void Initialize(string endpoint, Aliyun.Credentials.Client credential)
        {
            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentException("Endpoint cannot be null or empty.", nameof(endpoint));
            }
            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential), "Credential cannot be null.");
            }
            _endpoint = endpoint;
            _credential = credential;
        }
        public static AlibabaCloud.SDK.Ecs20140526.Client Instance => _instance.Value;
    }
    public class Program
    {
        public static async Task Main(string[] args)
        {
            // Initialize the EcsClient.
            EcsClient.Initialize("ecs.cn-hangzhou.aliyuncs.com", Credential.Instance);
            Action task = () =>
            {
                try
                {
                    var credential = Credential.Instance.GetCredential();
                    Console.WriteLine(DateTime.Now);
                    Console.WriteLine($"AK ID: {credential.AccessKeyId}, AK Secret: {credential.AccessKeySecret}, STS Token: {credential.SecurityToken}");
                    var ecsClient = EcsClient.Instance;
                    var request = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
                    var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
                    var response = ecsClient.DescribeRegionsWithOptions(request, runtime);
                    Console.WriteLine($"Invoke result: {response.StatusCode}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"ECS client execution failed: {ex.Message}");
                }
            };
            // Run the task immediately.
            task();
            // Start asynchronous tasks concurrently.
            var tasks = new[]
            {
                ScheduleTaskAsync(task, 600),
                ScheduleTaskAsync(task, 4200),
                ScheduleTaskAsync(task, 4300)
            };
            await Task.WhenAll(tasks);
            Console.WriteLine("All tasks completed.");
        }
        private static async Task ScheduleTaskAsync(Action task, int delaySeconds)
        {
            await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
            task();
        }
    }
}
2025/5/29 10:33:24
AK ID: STS.NVR3xxx P8KrfgTK, AK Secret: 6hsZk211xxx
        PeZZ8NHSBeQo, STS Token: CAISxAJ1q6Ft5B2yf5jIr5XneN+ChrwS1It+pcEXr0DkFNMReiaL/qTz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtBkQt5I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     JlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAsg    3PjcmYvy1dKzlhvI856BxNHBq+A748VMgj01iX9IIPPtJO3TwsQdpz0agaAFJZJGZS4RxwNkWL934H/nip/ameLEvxylbsU0x8]AMGRtHmlzYuolmGovqyeKhpDOT+H0am7tG2LvzKHoyVN8Kuck/qb/JAX/
xV1mHcLp3iPma8q+9xboP81YeU06c0vy   bzA2n7QI37852WyAA
Invoke result: 200
2025/5/29 10:43:25
AK ID: STS.NVR3xxx P8KrfgTK, AK Secret: 6hsZk211xxx
        PeZZ8NHSBeQo, STS Token: CAISxAJ1q6Ft5B2yf5jIr5XneN+ChrwS1It+pcEXr0DkFNMReiaL/qTz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtBkQt5I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     JlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAsg    3PjcmYvy1dKzlhvI856BxNHBq+A748VMgj01iX9IIPPtJO3TwsQdpz0agaAFJZJGZS4RxwNkWL934H/nip/ameLEvxylbsU0x8]AMGRtHmlzYuolmGovqyeKhpDOT+H0am7tG2LvzKHoyVN8Kuck/qb/JAX/
xV1mHcLp3iPma8q+9xboP81YeU06c0vy   bzA2n7QI37852WyAA
Invoke result: 200
2025/5/29 11:43:25
AK ID: STS.NWuFxxx BwvauFkU, AK Secret: 6fBbjmvd2T
        ChJTi9gPixZE, STS Token: CAISxAJ1q6Ft5B2yf5jIrSTAG/74uLB13aeARFwQlYXe/lNmoPAtzz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtdxAt7I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     iJlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAtQ    JU1tKDlwTxgBGOFKIQQrKj9PMSqhAcLJtS6MDE7NJKbt10KxV8Qdpz0agaAE7zrIhzsIKFMhIAyquB0Z8/YXeYdmswQUMbqmr+0gX306/0U9iWS612r6AalQSomcAD0eijKFnE8PFyx3YifekzIBCjr17TR
ujPRXpMzvxuXfvzz9eszDB0o0AXX5gTQ    IKDI4Y7necJANrPiAA
Invoke result: 200
2025/5/29 11:45:05
AK ID: STS.NWuPxxx bwvauFkU, AK Secret: 6fBbjmvd2T
        ChJTi9gPixZE, STS Token: CAISxAJ1q6Ft5B2yf5jIrSTAG/74uLB13aeARFwQlYXe/lNmoPAtzz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtdxAt7I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     iJlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAtQ    U1U1tKDlwTxgBGOFKIQQrKj9PMSqhAcLJtS6MDE7NJKbt10KxV8Qdpz0agaAE7zrIhzsIKFMhIAyquB0Z8/YXeYdmswQUMbqmr+0gX306/0U9iWS612r6AalQSomcAD0eijKFnE8PFyx3YifekZIBCjr17TR
ujPRXpMzvxuXfvzz9eszDB0o0AXX5gTQ    IKDI4Y7necJANrPiAA
Invoke result: 200
All tasks completed.

Análise baseada na saída do log:

  • Na primeira chamada, o cache está vazio. O sistema recupera uma credencial com base na sua configuração e a armazena no cache.

  • A segunda chamada usa a mesma credencial da primeira, indicando que ela foi recuperada do cache.

  • Na terceira chamada, a credencial em cache expirou. Seu tempo de expiração (RoleSessionExpiration) é de 3.600 segundos, mas esta chamada ocorre 4.200 segundos após a primeira. Consequentemente, o mecanismo de atualização automática do SDK busca uma nova credencial e atualiza o cache.

  • A quarta chamada usa a mesma credencial da terceira, confirmando que o cache foi atualizado.

Documentos relacionados