Todos os produtos
Search
Central de documentação

Alibaba Cloud SDK:Gerenciar 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.

Contexto

Uma credencial é um conjunto de informações que verifica a identidade de um usuário. Para entrar em um sistema, o usuário deve fornecer credenciais válidas. Os tipos comuns de credenciais incluem:

  1. Um AccessKey é uma credencial de longo prazo para uma conta Alibaba Cloud ou um usuário RAM. Trata-se de um par de chaves composto por um AccessKey ID e um AccessKey secret.

  2. Um token STS é uma credencial de acesso temporário para uma função RAM. Ele inclui um período de validade configurável e permissões de acesso. Para mais informações, consulte O que é STS.

  3. Um bearer token é uma credencial usada para autenticação e autorização.

Pré-requisitos

Instalar o Alibaba Cloud Credentials

Se o Alibaba Cloud Credentials já estiver instalado, pule esta etapa. Recomendamos usar a dependência mais recente do Alibaba Cloud Credentials para garantir suporte total a todos os tipos de credenciais. Para obter informações sobre todas as versões lançadas, consulte Alibaba Cloud Credentials.

Instale o Alibaba Cloud Credentials usando um dos seguintes métodos:

  • Método 1: Use go get para instalar o Alibaba Cloud Credentials:

    $ go get -u github.com/aliyun/credentials-go
  • Método 2: Se você usar dep para gerenciar dependências, execute o seguinte comando:

    dep ensure -add github.com/aliyun/credentials-go

Ferramenta Credentials: Parâmetros

A struct Config no pacote github.com/aliyun/credentials-go/credentials define os parâmetros de configuração da ferramenta de credenciais. Use o parâmetro obrigatório type para especificar o tipo de credencial e configure os parâmetros correspondentes. A tabela a seguir lista os valores válidos para o parâmetro type e os parâmetros compatíveis com cada tipo de credencial. Nesta tabela, √ indica um parâmetro obrigatório, - indica um parâmetro opcional e × significa que o parâmetro não é compatível.

Nota

Evite usar tipos de credenciais ou parâmetros não listados na tabela abaixo.

Tipo

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

AccessKeyId: O AccessKey ID.

√

√

√

×

×

×

×

AccessKeySecret: O AccessKey secret.

√

√

√

×

×

×

×

SecurityToken: O token STS.

×

√

-

×

×

×

×

RoleArn: O Alibaba Cloud Resource Name (ARN) da função RAM.

×

×

√

×

√

×

×

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

×

×

-

×

-

×

×

RoleName: O nome da função RAM.

×

×

×

-

×

×

×

DisableIMDSv1: Defina como true para impor o modo de endurecimento de segurança. O valor padrão é false.

×

×

×

-

×

×

×

BearerToken: O bearer token.

×

×

×

×

×

×

√

Policy: A política personalizada.

×

×

-

×

-

×

×

RoleSessionExpiration: O tempo de expiração da sessão, em segundos. O valor padrão é 3.600.

×

×

-

×

-

×

×

OIDCProviderArn: O Alibaba Cloud Resource Name (ARN) do provedor de identidade (IdP) OpenID Connect (OIDC).

×

×

×

×

√

×

×

OIDCTokenFilePath: O caminho para o arquivo de token OIDC.

×

×

×

×

√

×

×

ExternalId: O ID externo da função. Este ID ajuda a prevenir o problema de "confused deputy". Para mais informações, consulte Usar ExternalId para prevenir o problema de confused deputy.

×

×

-

×

×

×

×

Url: A URI da credencial. Este valor é definido usando o método SetURLCredential(v string).

×

×

×

×

×

√

×

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

×

×

-

×

-

×

×

Timeout: O tempo limite de leitura HTTP, em milissegundos. O valor padrão é 5.000.

×

×

-

-

-

-

×

ConnectTimeout: O tempo limite de conexão HTTP, em milissegundos. O valor padrão é 10.000.

×

×

-

-

-

-

×

Inicializar um 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 mostram como usar a ferramenta. Selecione o método mais adequado ao seu cenário.

Importante
  • Codificar rigidamente (hard-code) 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.

  • Use 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: usar a cadeia de provedores de credenciais padrão

Se você inicializar o cliente Credentials sem parâmetros, o Credentials usará a cadeia de provedores de credenciais padrão. Para saber mais sobre como as credenciais padrão são carregadas, consulte Cadeia de provedores de credenciais padrão.

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Pass nil to use the default credential provider chain.
	credential, err := credentials.NewCredential(nil)
	config := &openapi.Config{}
        config.Credential = credential
        // The code to initialize a cloud product client is omitted. See the API call example for details.
}

Exemplo de chamada de API

Este exemplo mostra como chamar a operação DescribeRegions do ECS. Para executar este exemplo, instale o ECS SDK para Go.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Create a credential from the default provider chain.
	credentialClient, _err := credentials.NewCredential(nil)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Set the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Set the credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation and get the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Método 2: AccessKey

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

Aviso

Uma conta Alibaba Cloud (conta raiz) tem 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.

package main
import (
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("access_key").
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	akCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
	config.Credential = akCredential
	// Code to initialize a cloud product client is omitted. See the API call example for details.
}

Exemplo de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Para executá-lo, instale primeiro o ECS SDK.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	// Initialize the credential client with an AccessKey pair.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("access_key").
		// Set your AccessKey ID.
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		// Set your AccessKey secret.
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Configure the credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize a DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Método 3: Token STS

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

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("sts").
		// Get the AccessKey ID from the environment variable.
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		// Get the AccessKey secret from the environment variable.
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
		// Get the security token from the environment variable.
		SetSecurityToken(os.Getenv("ALIBABA_CLOUD_SECURITY_TOKEN"))
	stsCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
        config.Credential = stsCredential
        // The initialization code for the cloud product client is omitted. For details, see the API call examples.
}

Chamada de API

Este exemplo ilustra como invocar a operação DescribeRegions do ECS. Para executar este exemplo, instale o ECS SDK e o STS SDK.

package main
import (
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	sts20150401 "github.com/alibabacloud-go/sts-20150401/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Create an STS client and call the AssumeRole operation to obtain an STS token.
	stsConfig := &openapi.Config{}
	stsConfig.SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
	stsConfig.SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
	stsConfig.SetEndpoint("sts.cn-hangzhou.aliyuncs.com")
	client, _err := sts20150401.NewClient(stsConfig)
	if _err != nil {
		panic(_err)
	}
	assumeRoleRequest := &sts20150401.AssumeRoleRequest{}
	// The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set RoleArn by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
	assumeRoleRequest.SetRoleArn("<RoleArn>")
	// The role session name. You can set RoleSessionName by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
	assumeRoleRequest.SetRoleSessionName("<RoleSessionName>")
	assumeRoleRequest.SetDurationSeconds(3600)
	result, _err := client.AssumeRole(assumeRoleRequest)
	if _err != nil {
		panic(_err)
	}
	assumeRoleResponseBodyCredentials := result.Body.Credentials
	// Use an STS token to initialize the Credentials client.
	credentialsConfig := new(credentials.Config).
		// Specify the credential type.
		SetType("sts").
		SetAccessKeyId(*assumeRoleResponseBodyCredentials.AccessKeyId).
		SetAccessKeySecret(*assumeRoleResponseBodyCredentials.AccessKeySecret).
		SetSecurityToken(*assumeRoleResponseBodyCredentials.SecurityToken)
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-hangzhou.aliyuncs.com")
	// Configure the credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation and retrieve the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Método 4: AK e RamRoleArn

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 SetPolicy para restringir a função RAM a um conjunto menor de permissões.

package main
import (
	"fmt"
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("ram_role_arn").
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
		// Specifies the ARN of the RAM role to assume, such as `acs:ram::123456789012****:role/adminrole`. You can also set this with the `ALIBABA_CLOUD_ROLE_ARN` environment variable.
		SetRoleArn("<RoleArn>").
		// A custom name for the role session. You can also set this with the `ALIBABA_CLOUD_ROLE_SESSION_NAME` environment variable.
		SetRoleSessionName("<RoleSessionName>").
		// Optional. An inline policy that further restricts the permissions of the temporary credentials. For example, `{"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}`
		SetPolicy("<Policy>").
		// Optional. The session expiration time in seconds.
		SetRoleSessionExpiration(3600).
		// Optional. The external ID used to prevent the confused deputy problem.
		SetExternalId("ExternalId").
		// Optional. The STS endpoint. The default is sts.aliyuncs.com. For better network performance, use a region-specific endpoint closer to your application.
		SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com")
	arnCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
        config.Credential = arnCredential
        // This example omits the client initialization code. For more information, see the API call example.
}
Nota

Para saber mais sobre o ID externo, consulte Prevenir o problema de confused deputy com IDs externos.

Exemplo de API

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

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	// Initialize the credential configuration with a RAM role ARN.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("ram_role_arn").
		// The AccessKey ID.
		SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).
		// The AccessKey Secret.
		SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")).
		// The ARN of the RAM role to assume. This can be set with the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
		SetRoleArn("<RoleArn>").
		// A custom name for the role session. This can be set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
		SetRoleSessionName("<RoleSessionName>").
		// Optional. An inline policy to further restrict permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
		SetPolicy("<Policy>").
		// Optional. The session expiration time in seconds.
		SetRoleSessionExpiration(3600).
		// Optional. The STS endpoint. The default is sts.aliyuncs.com. For better network performance, use a region-specific endpoint closer to your application.
		SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com")
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Assign the created credential to the ECS configuration.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize runtime options.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation and retrieve the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

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. Assim, as aplicações nessas instâncias podem usar a ferramenta de credenciais para obter automaticamente um token STS e inicializar o cliente de credenciais.

Por padrão, a ferramenta de credenciais acessa o servidor de metadados do ECS no modo de endurecimento de segurança (IMDSv2). Em caso de erro, a ferramenta reverte automaticamente para o modo normal para obter a credencial de acesso. Controle esse comportamento de reversão definindo o parâmetro disableIMDSv1 ou a variável de ambiente ALIBABA_CLOUD_IMDSV1_DISABLE:

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

  • Se definido como true, a ferramenta usa apenas o modo de endurecimento de segurança e lança uma exceção em caso de falha.

O suporte ao IMDSv2 depende da configuração do servidor.

Além disso, desative o acesso a credenciais via metadados da instância ECS definindo a variável de ambiente ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Nota
package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func _main(args []*string) {
	// Initialize a credentials client using an ECS RAM role.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("ecs_ram_role").
		// Optional. The name of the ECS RAM role. If left empty, the name is automatically retrieved. Set this parameter to reduce API calls. You can also set it using the ALIBABA_CLOUD_ECS_METADATA environment variable.
		SetRoleName("<RoleName>")
	// Optional, defaults to false. A value of `true` enforces security hardening mode (IMDSv2). When set to `false`, the SDK first attempts to retrieve credentials in security hardening mode and falls back to normal mode (IMDSv1) if the attempt fails.
	// credentialsConfig.SetDisableIMDSv1(true)
	credentialClient, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
        config.Credential = credentialClient
        // The code to initialize a cloud product client with this config object is omitted. For details, see the API call example.
}

Exemplo de chamada de API

Este exemplo mostra como chamar a operação DescribeRegions do ECS. Instale o ECS SDK antes de executar o exemplo.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Initialize the Credentials client by using an ECS RAM role.
	credentialsConfig := new(credentials.Config).
		// Specifies the credential type.
		SetType("ecs_ram_role").
		// Optional. The role name. If omitted, the name is automatically retrieved. Specifying this parameter is recommended to reduce requests. You can also set the role name by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
		SetRoleName("<RoleName>")
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Sets the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Sets the client credential.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize the runtime configuration.
	runtime := &util.RuntimeOptions{}
	// Calls the DescribeRegions operation and retrieves the response.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Método 6: Usar OIDCRoleArn

Caso use OIDC para autenticação e tenha 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 para a 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 suportam atualização automática. Para mais informações, consulte Atualização automática de credenciais de sessão. Por exemplo, se sua aplicação roda em um cluster Container Service for Kubernetes (ACK) com RRSA ativado, a ferramenta Credentials pode 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 serviços da Alibaba Cloud.

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.comcom/aliyun/credentials-go/credentials"
	"os"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("oidc_role_arn").
		// The OIDC provider ARN. You can set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
		SetOIDCProviderArn(os.Getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN")).
		// The OIDC token file path. You can set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
		// The RAM role ARN. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
		SetRoleArn(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")).
		// The role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
		SetRoleSessionName(os.Getenv("ALIBABA_CLOUD_ROLE_SESSION_NAME")).
		// Optional. Specifies an inline policy to further restrict permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
		SetPolicy("<Policy>").
		// Optional. Specifies the session expiration in seconds.
		SetRoleSessionExpiration(3600).
		// Optional. The STS endpoint. The default is sts.aliyuncs.com. For improved network connectivity, use a region-specific endpoint.
		SetSTSEndpoint("sts.cn-hangzhou.aliyuncs.com")
	oidcCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
	config.Credential = oidcCredential
	// Code for initializing a cloud product client with the config object is omitted. For more information, see the API call example.
}

Exemplo de API

Este exemplo demonstra como chamar a operação DescribeRegions do ECS. Para executar este código, instale o ECS SDK para Go.

package main
import (
	"os"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func main() {
	// Initialize the Credentials client by using an OIDC Role ARN.
	credentialsConfig := new(credentials.Config).
		// The credential type.
		SetType("oidc_role_arn").
		// The ARN of the OIDC identity provider. Set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
		SetOIDCProviderArn(os.Getenv("ALIBABA_CLOUD_OIDC_PROVIDER_ARN")).
		// The file path of the OIDC token. Set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
		SetOIDCTokenFilePath(os.Getenv("ALIBABA_CLOUD_OIDC_TOKEN_FILE")).
		// The ARN of the RAM role. Set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
		SetRoleArn(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")).
		// The role session name. Set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
		SetRoleSessionName(os.Getenv("ALIBABA_CLOUD_ROLE_SESSION_NAME")).
		// Optional. An inline policy that further restricts permissions. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
		SetPolicy("<Policy>").
		// The session duration in seconds.
		SetRoleSessionExpiration(3600)
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Assign the credential to the client configuration.
	ecsConfig.Credential = credentialClient
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize the runtime configuration.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Método 7: Usar uma credencial URI

Encapsule o Security Token Service (STS) atrás de uma 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 essa URI para buscar um token STS e utilizá-lo como credencial de acesso. Credenciais obtidas dessa maneira suportam atualização automática. Para mais detalhes, consulte Atualização automática de credenciais de sessão.

package main
import (
	"github.com/aliyun/credentials-go/credentials"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("credentials_uri").
                // The credential URI. Format: http://local_or_remote_uri/. You can also set this by using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
		SetURLCredential("<CredentialsUri>")
	uriCredential, err := credentials.NewCredential(credentialsConfig)
	config := &openapi.Config{}
	config.Credential = uriCredential
	// The client initialization code for the cloud product is omitted for brevity. For more information, see the API call example.
}

A URI deve obedecer aos seguintes critérios:

  • Suportar requisições GET.

  • O corpo da resposta deve ter a seguinte estrutura:

    {
      "AccessKeySecret": "AccessKeySecret",
      "AccessKeyId": "AccessKeyId",
      "Expiration": "2021-09-26T03:46:38Z",
      "SecurityToken": "SecurityToken"
    }

Exemplo de API

Este exemplo ilustra como invocar a operação DescribeRegions do ECS. A execução deste exemplo requer o ECS SDK para Go.

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func main() {
	config := new(credentials.Config).
		SetType("credentials_uri").
		// The credential URI, for example, http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
		SetURLCredential("<CredentialsUri>")
	uriCredential, _err := credentials.NewCredential(config)
	if _err != nil {
		panic(_err)
	}
	ecsConfig := &openapi.Config{}
	// Configure the service endpoint.
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	// Configure the credential.
	ecsConfig.Credential = uriCredential
	// Initialize the ECS client.
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	// Initialize the DescribeRegions request.
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	// Initialize the runtime configuration.
	runtime := &util.RuntimeOptions{}
	// Call the DescribeRegions operation.
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Método 8: Usar bearer token

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

package main
import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials"
)
func main() {
	credentialsConfig := new(credentials.Config).
		SetType("bearer").
		// Enter your bearer token.
		SetBearerToken("<BearerToken>")
	bearerCredential, err := credentials.NewCredential(credentialsConfig)
	if err != nil {
		return
	}
	config := &openapi.Config{}
	config.Credential = bearerCredential
	// This example omits the client initialization code. See the API call example for the complete implementation.
}

Exemplo de API

Este exemplo mostra como chamar a operação GetInstance do Cloud Call Center. Para executar este exemplo, instale primeiro o CCC SDK.

package main
import (
	ccc20200701 "github.com/alibabacloud-go/ccc-20200701/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	credentials "github.com/aliyun/credentials-go/credentials"
)
func _main() (_err error) {
	// Initialize the credential client by using a bearer token.
	credentialsConfig := new(credentials.Config).
		// Specify the credential type.
		SetType("bearer").
		SetBearerToken("<BearerToken>")
	credentialClient, _err := credentials.NewCredential(credentialsConfig)
	if _err != nil {
		return _err
	}
	// Initialize the CCC client with the credential client.
	config := &openapi.Config{}
	config.Endpoint = tea.String("ccc.cn-shanghai.aliyuncs.com") // Specify the service endpoint.
	config.Credential = credentialClient                         // Configure the credential.
	cccClient, _err := ccc20200701.NewClient(config)
	if _err != nil {
		return _err
	}
	getInstanceRequest := &ccc20200701.GetInstanceRequest{
		InstanceId: tea.String("ccc-test"),
	}
	runtime := &util.RuntimeOptions{}
	response, _err := cccClient.GetInstanceWithOptions(getInstanceRequest, runtime)
	if _err != nil {
		return _err
	}
	panic(response.Body.String())
}
func main() {
	err := _main()
	if err != nil {
		panic(err)
	}
}

Método 9: Usar CLIProfileCredentialsProvider

Recupera credenciais de acesso do arquivo de configuração de credenciais da Alibaba Cloud CLI, config.json.

package main
import (
	"github.com/aliyun/credentials-go/credentials"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	"github.com/aliyun/credentials-go/credentials/providers"
)
func main() {
	// CLIProfileCredentialsProvider
	provider, err := providers.NewCLIProfileCredentialsProviderBuilder().
	        // Optional. Specifies the profile name. The resolution precedence is: explicit profileName > ALIBABA_CLOUD_CONFIG_FILE environment variable > 'current' profile in config.json.
		WithProfileName("<PROFILE_NAME>"). 
		// Optional. Specifies the path to the configuration file (which must be a .json file). The resolution precedence is: the specified profileFile > the ALIBABA_CLOUD_CONFIG_FILE environment variable > the default path ~/.aliyun/config.json.
		WithProfileFile("<PROFILE_FILE_PATH>"). 
		Build()
	if err != nil {
		return
	}
	credential := credentials.FromCredentialsProvider("cli_profile", provider)
	config := &openapi.Config{}
	config.Credential = credential
	// The code for initializing a cloud product client with the config object is omitted for brevity.
}

Configure as credenciais usando a Alibaba Cloud CLI ou crie manualmente o arquivo de configuração config.json no seguinte caminho:

  • Linux: ~/.aliyun/config.json

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

O conteúdo do arquivo deve estar no seguinte formato:

{
  "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
    },
    {
      "name": "<PROFILE_NAME6>",
      "mode": "CloudSSO",
      "cloud_sso_sign_in_url": "https://******/login",
      "access_token": "eyJraWQiOiJiYzViMzUwYy******",
      "cloud_sso_access_token_expire": 1754316142,
      "cloud_sso_access_config": "ac-00s1******",
      "cloud_sso_account_id": "151266******"
    }
  ]
}

No arquivo config.json, use o parâmetro mode para especificar o tipo de credencial:

  • AK: Usa uma Access Key.

  • StsToken: Usa um token STS.

  • RamRoleArn: Assume uma função RAM usando seu ARN para obter a credencial.

  • EcsRamRole: Assume a função RAM anexada a uma instância ECS para obter a credencial.

  • OIDC: Usa um ARN de provedor OIDC e um token OIDC para obter a credencial.

  • ChainableRamRoleArn: Usa uma cadeia de funções, onde source_profile especifica o nome de outras credenciais no arquivo de configuração config.json para recuperar novas credenciais.

  • CloudSSO: Usa a credencial obtida por um usuário Cloud SSO através da Alibaba Cloud CLI.

    Nota

    Credenciais CloudSSO exigem a versão 1.4.7 ou posterior do github.com/aliyun/credentials-go, e a configuração só pode ser obtida usando a Alibaba Cloud CLI. Para mais informações, consulte Usar a CLI para fazer login no CloudSSO e acessar recursos da Alibaba Cloud.

Após concluir a configuração, o provedor inicializa uma credencial com base no nome do perfil especificado.

Exemplo de chamada de API

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

package main
import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
	"github.com/aliyun/credentials-go/credentials/providers"
)
func main() {
	// CLIProfileCredentialsProvider
	provider, err := providers.NewCLIProfileCredentialsProviderBuilder().
		WithProfileName("SSOProfile"). // Optional. Defaults to 'current' in config.json.
		// WithProfileFile("/path/to/config.json"). // Optional. Defaults to ~/.aliyun/config.json.
		Build()
	if err != nil {
		return
	}
	credentialClient := credentials.FromCredentialsProvider("cli_profile", provider)
	// Use the credential to initialize the ECS client.
	ecsConfig := &openapi.Config{}
	ecsConfig.Endpoint = tea.String("ecs.cn-beijing.aliyuncs.com")
	ecsConfig.Credential = credentialClient
	ecsClient, _err := ecs20140526.NewClient(ecsConfig)
	describeInstancesRequest := &ecs20140526.DescribeRegionsRequest{}
	runtime := &util.RuntimeOptions{}
	response, _err := ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime)
	if _err != nil {
		panic(_err)
	}
	panic(response.Body.String())
}

Cadeia de provedores de credenciais padrão

Quando ambientes de desenvolvimento e produção exigem tipos diferentes de credenciais, é comum escrever código condicional para recuperá-las com base no ambiente atual. A cadeia de provedores de credenciais padrão simplifica esse processo, permitindo usar uma única base de código e controlar a recuperação de credenciais por meio de configuração externa. Ao inicializar um cliente de credenciais chamando NewCredential() sem nenhum parâmetro, o Alibaba Cloud SDK busca credenciais na seguinte ordem.

1. 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 vazios, a cadeia de provedores os usará como credencial padrão.

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

2. Função RAM OIDC

Se nenhuma credencial tiver 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 de 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. Arquivo config.json

Caso não sejam encontradas credenciais de maior precedência, a ferramenta Credentials carrega o arquivo config.json. Os caminhos padrão para este arquivo são:

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

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

Nota

A partir da versão github.com/aliyun/credentials-go@1.4.4, personalize o caminho do arquivo config.json usando a variável de ambiente ALIBABA_CLOUD_CONFIG_FILE. Esta variável de ambiente tem precedência sobre o caminho padrão.

Para configurar credenciais com este método, use a Alibaba Cloud CLI ou crie manualmente um arquivo config.json no caminho apropriado. O exemplo a seguir mostra o formato do arquivo:

{
    "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
        },
        {
            "name": "<PROFILE_NAME6>",
            "mode": "CloudSSO",
            "cloud_sso_sign_in_url": "https://******/login",
            "access_token": "eyJraWQiOiJiYzViMzUwYy******",
            "cloud_sso_access_token_expire": 1754316142,
            "cloud_sso_access_config": "ac-00s1******",
            "cloud_sso_account_id": "151266******"
        },
        {
            "name": "<PROFILE_NAME7>",
            "mode": "OAuth",
            "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
            "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
            "sts_token": "<SECURITY_TOKEN>",
            "region_id": "<REGION_ID>",
            "output_format": "json",
            "language": "<zh|en>",
            "sts_expiration": "<STS_EXPIRATION>",
            "oauth_access_token": "<OAUTH_ACCESS_TOKEN>",
            "oauth_refresh_token": "<OAUTH_REFRESH_TOKEN>",
            "oauth_access_token_expire": 1754316142,
            "oauth_site_type": "<CN|EN>"
        }
    ]
}

No arquivo config.json, use o parâmetro mode para especificar diferentes tipos de credenciais:

  • AK: Usa a chave de acesso de um usuário como credenciais.

  • StsToken: Usa um token STS como credenciais.

  • RamRoleArn: Usa um ARN de função RAM para obter credenciais.

  • EcsRamRole: Usa a função RAM anexada a uma instância ECS para obter credenciais.

  • OIDC: Usa um ARN de provedor OIDC e um token OIDC para obter credenciais.

  • ChainableRamRoleArn: Implementa uma cadeia de funções. Use o parâmetro source_profile para especificar outro perfil no arquivo config.json do qual obter novas credenciais.

  • OAuth: Usa credenciais obtidas fazendo login via OAuth através da Alibaba Cloud CLI.

  • CloudSSO: Usa credenciais obtidas por um usuário CloudSSO através da Alibaba Cloud CLI.

Nota

Após a configuração, o Credentials inicializa o cliente usando o perfil especificado no campo current do arquivo de configuração. Também é possível especificar um perfil definindo a variável de ambiente ALIBABA_CLOUD_PROFILE. Por exemplo, defina o valor de ALIBABA_CLOUD_PROFILE como client1.

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

Se não forem encontradas credenciais de maior precedência, o Credentials as obtém da função RAM anexada a uma instância ECS. Por padrão, o Credentials usa IMDSv2 para acessar o serviço de metadados do ECS e recuperar um token STS para a função RAM da instância ECS. Esse processo envolve duas requisições: a primeira para obter o nome da função do serviço de metadados e a segunda para recuperar as credenciais. Para reduzir isso a uma única requisição, especifique o nome da função RAM da instância diretamente definindo a variável de ambiente ALIBABA_CLOUD_ECS_METADATA. Se ocorrer um erro ao usar IMDSv2, o Credentials reverte automaticamente para IMDSv1. Controle esse comportamento de reversão definindo a variável de ambiente ALIBABA_CLOUD_IMDSV1_DISABLE:

  1. Quando definido como false, a ferramenta reverte para IMDSv1 para recuperar credenciais se a requisição IMDSv2 falhar.

  2. Quando definido como true, a ferramenta usa apenas IMDSv2. Se a requisição falhar, uma exceção será lançada.

O suporte do servidor ao IMDSv2 depende da configuração do seu servidor.

Também é possível desativar o acesso a credenciais pelo serviço de metadados do ECS definindo a variável de ambiente ALIBABA_CLOUD_ECS_METADATA_DISABLED=true.

Nota

5. URI de Credenciais

Caso nenhuma credencial tenha sido encontrada, a cadeia de provedores verifica a variável de ambiente ALIBABA_CLOUD_CREDENTIALS_URI. Se esta variável estiver definida e apontar para uma URI válida, a cadeia acessa a 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, suportam 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 de expirarem.

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.

package main
import (
	"fmt"
	"log"
	"os"
	"sync"
	"time"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	ecs20140526 "github.com/alibabacloud-go/ecs-20140526/v7/client"
	util "github.comcom/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/aliyun/credentials-go/credentials"
)
// Credential manages the singleton instance of Alibaba Cloud credentials.
type Credential struct {
	instance credentials.Credential
	once     sync.Once
}
var credentialInstance = &Credential{}
func GetCredentialInstance() credentials.Credential {
	credentialInstance.once.Do(func() {
		cfg := &credentials.Config{
			Type:                  tea.String("ram_role_arn"),
			AccessKeyId:           tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
			AccessKeySecret:       tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
			RoleArn:               tea.String(os.Getenv("ALIBABA_CLOUD_ROLE_ARN")),
			RoleSessionName:       tea.String("RamRoleArnTest"),
			RoleSessionExpiration: tea.Int(3600),
		}
		var err error
		credentialInstance.instance, err = credentials.NewCredential(cfg)
		if err != nil {
			log.Fatalf("Credential initialization failed: %v", err)
		}
	})
	return credentialInstance.instance
}
// EcsClient manages the singleton instance of the ECS client.
type EcsClient struct {
	instance *ecs20140526.Client
	once     sync.Once
}
var ecsClientInstance = &EcsClient{}
func GetEcsClientInstance(cred credentials.Credential) *ecs20140526.Client {
	ecsClientInstance.once.Do(func() {
		cfg := &openapi.Config{
			Endpoint:   tea.String("ecs.cn-hangzhou.aliyuncs.com"),
			Credential: cred,
		}
		var err error
		ecsClientInstance.instance, err = ecs20140526.NewClient(cfg)
		if err != nil {
			log.Fatalf("ECS client initialization failed: %v", err)
		}
	})
	return ecsClientInstance.instance
}
// Run the main task.
func runTask() {
	cred := GetCredentialInstance()
	credentialModel, err := cred.GetCredential()
	if err != nil {
		log.Printf("Failed to get credential: %v", err)
		return
	}
	fmt.Println(time.Now())
	fmt.Printf("AK ID: %s, AK Secret: %s, STS Token: %s\n",
		*credentialModel.AccessKeyId,
		*credentialModel.AccessKeySecret,
		*credentialModel.SecurityToken)
	ecsClient := GetEcsClientInstance(cred)
	req := &ecs20140526.DescribeRegionsRequest{}
	runtime := &util.RuntimeOptions{}
	resp, err := ecsClient.DescribeRegionsWithOptions(req, runtime)
	if err != nil {
		log.Printf("ECS API call failed: %v", err)
		return
	}
	fmt.Printf("Invoke result: %d\n", *resp.StatusCode)
}
func main() {
	done := make(chan bool)
	// Start a goroutine to run scheduled tasks.
	go func() {
		tick := time.NewTicker(1 * time.Second)
		defer tick.Stop()
		executionCount := 0
		delays := []time.Duration{0, 600, 3600, 100} // Delay in seconds.
		for {
			select {
			case <-tick.C:
				if executionCount < len(delays) {
					delay := delays[executionCount]
					time.Sleep(delay * time.Second)
					runTask()
					executionCount++
				} else {
					close(done)
					return
				}
			}
		}
	}()
	<-done
	fmt.Println("All tasks completed. Exiting...")
}
2025-05-29 10:56:24.7142698 +0800 CST m=+1.418627901
AK ID: STS.NXFN xxx 33d7Da, AK Secret: 3QdoQASHSyt xxx UGNjZaHsEGXZXc, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5vZBf3Biotj1o6MQGjFgTI2eLwfi/Lvgzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7VsDs194Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx m5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAvw3VhNiQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx D2hT+Bi3HLQztLtlrnMQdpz0agAFDeioHfrugVbFZyY9ggw28Pyx4ckcndsp1cWIU/kwT5HYClH6X7ArciY+H1V01Nh1W7dDFIiwn5htgzQkn1K2xXKA1SNzCjy076rXe7F+BNGES3mUPuTTk
irb467Kb6f3SHj7 xxx J6DPHSj/VzDSAA
Invoke result: 200
2025-05-29 11:06:25.3225563 +0800 CST m=+602.026914401
AK ID: STS.NXFN xxx 33d7Da, AK Secret: 3QdoQASHSyt xxx UGNjZaHsEGXZXc, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5vZBf3Biotj1o6MQGjFgTI2eLwfi/Lvgzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7VsDs194Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx m5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAvw3VhNiQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx D2hT+Bi3HLQztLtlrnMQdpz0agAFDeioHfrugVbFZyY9ggw28Pyx4ckcndsp1cWIU/kwT5HYClH6X7ArciY+H1V01Nh1W7dDFIiwn5htgzQkn1K2xXKA1SNzCjy076rXe7F+BNGES3mUPuTTk
irb467Kb6f3SHj7 xxx J6DPHSj/VzDSAA
Invoke result: 200
2025-05-29 12:06:26.039859 +0800 CST m=+4202.744217101
AK ID: STS.NWDS xxx 73kVg5u, AK Secret: C3tJCLkszB3 xxx PHGcUroGruw8D, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5TxGOKBjrYY1ZCEWmrFr2YUO7xHuaKelzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7Vtz5F96Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx 5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAsQnUp9tQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx 2hT+Bi3HLQztcMoybMQdpz0agAExoac2PSXrXSXyh4J+ekl0xNIztOFEAJJ2qTkuUgP1AKZIsZYdnX+yHJ1XJpD/yd6pKCEmUSzBwR+Q+S1BmhDANmVRzwUG8QJwxD6bTEvjUwhpGUOKLJL6b
FoBpJJ4WDZRliiw0 xxx y8sGj81a/iiAA
Invoke result: 200
2025-05-29 12:08:06.3556621 +0800 CST m=+4303.060020201
AK ID: STS.NWDS xxx 73kVg5u, AK Secret: C3tJCLkszB3 xxx PHGcUroGruw8D, STS Token:
CAISxAJ1q6Ft5B2yfSjIr5TxGOKBjrYY1ZCEWmrFr2YUO7xHuaKelzz2IHhMeXZoA4YsPw2mmFW6/sdlqdJQpp/QkjJRNF20plM7Vtz5F96Ipbng4YfgbiJREKxaXeiruwDsz9SNTCAITPD3nPii50x5bjaDymRcbLGJaVi1lhHL91N0vCGlggPtp
NIRZ4o8I3LGbyMe xxx 5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWSMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif5I/DXQEIvUTYbreL6L9mNxRkY6UgHKpJvCxxBmi0fUW5fe3VvPUtVk9O0y3LAsQnUp9tQSHHGKYZGRWSp
XcU6Fux60PxycOS xxx 2hT+Bi3HLQztcMoybMQdpz0agAExoac2PSXrXSXyh4J+ekl0xNIztOFEAJJ2qTkuUgP1AKZIsZYdnX+yHJ1XJpD/yd6pKCEmUSzBwR+Q+S1BmhDANmVRzwUG8QJwxD6bTEvjUwhpGUOKLJL6b
FoBpJJ4WDZRliiw0 xxx y8sGj81a/iiAA
Invoke result: 200
All tasks completed. Exiting...

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 depois a armazena no cache.

  • A segunda chamada usa a mesma credencial que a 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 é feita 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 que a terceira, confirmando que o cache foi atualizado.

Documentos relacionados