All Products
Search
Document Center

Configure credentials

Last Updated: Feb 23, 2022

If you use an AccessKey pair as an access credential, you must configure the credential when you initialize the client. This topic provides sample code.

Notice

Keep the code that contains your AccessKey pair confidential. For example, do not commit the code to public GitHub projects. If you commit the code, your Alibaba Cloud account may be compromised.

Use an AccessKey pair

The following code shows how to use github.com/alibabacloud-go/darabonba-openapi/client to configure credentials:

import (
 "fmt"
 "strings"

 facebody "github.com/alibabacloud-go/facebody-20191230/client"
 openapi "github.com/alibabacloud-go/darabonba-openapi/client"
 util "github.com/alibabacloud-go/tea-utils/service"
)

func main() {
 config := new(openapi.Config)

 // Use an AccessKey pair to initialize config.
 config.SetAccessKeyId("ACCESS_KEY_ID").
  SetAccessKeySecret("ACCESS_KEY_SECRET").
  SetRegionId("cn-hangzhou").
  SetEndpoint("facebody.cn-hangzhou.aliyuncs.com")

 // Create a client.
 client, err := facebody.NewClient(config)
 if err != nil {
  panic(err)
 }

 // Initialize runtimeObject.
 runtimeObject := new(util.RuntimeOptions).SetAutoretry(false).
  SetMaxIdleConns(3)

 // Initialize request.
 request := new(facebody.DetectFaceRequest)

 // Call an API operation.
 resp, err := client.DetectFace(request, runtimeObject)
 if err != nil {
  fmt.Println(err.Error())
 }
 fmt.Println(resp)
}

You can also use SDK Credentials to configure credentials. This method is commonly used and supports multiple types of credentials. The following section describes how to use SDK Credentials.

Use the SDK Credentials package

Install SDK Credentials

  • Make sure that Go 1.10.x or a later version is installed on your system.

Run the following go get command to download and install Go:

$ go get -u github.com/aliyun/credentials-go

If you use dep to manage your dependency package, you can run the following command:

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

You must have an Alibaba Cloud account and an AccessKey pair to use Alibaba Cloud Darabonba SDK for Go.

Configure an AccessKey pair

You can log on to the User Management console to configure AccessKey pairs. An AccessKey pair is granted full permissions on the resources that belong to an Alibaba Cloud account or a RAM user. Keep your AccessKey pair confidential. For security reasons, we recommend that you do not provide the AccessKey pair of your Alibaba Cloud account to a developer. You can create a RAM user and grant permissions to the RAM user. This way, the developer can use the AccessKey pair of the RAM user to call API operations.

import (
 "fmt"

 "github.com/aliyun/credentials-go/credentials"
)

func main(){
 config := new(credentials.Config).
  // Which type of credential you want
  SetType("access_key").
  // AccessKeyId of your account
  SetAccessKeyId("AccessKeyId").
  // AccessKeySecret of your account
  SetAccessKeySecret("AccessKeySecret")

 akCredential, err := credentials.NewCredential(config)
 if err != nil {
  return
 }
 accessKeyId, err := akCredential.GetAccessKeyId()
 accessSecret, err := akCredential.GetAccessKeySecret()
 credentialType := akCredential.GetType()
 fmt.Println(accessKeyId, accessSecret, credentialType)
}

Configure an STS token

You can apply for a temporary security credential (TSC) from Security Token Service (STS) and specify the TSC as a temporary credential in the Darabonba SDK.

import (
 "fmt"

 "github.com/aliyun/credentials-go/credentials"
)

func main() {
 config := new(credentials.Config).
  // Which type of credential you want
  SetType("sts").
  // AccessKeyId of your account
  SetAccessKeyId("AccessKeyId").
  // AccessKeySecret of your account
  SetAccessKeySecret("AccessKeySecret").
  // Temporary Security Token
  SetSecurityToken("SecurityToken")

 stsCredential, err := credentials.NewCredential(config)
 if err != nil {
  return
 }
 accessKeyId, err := stsCredential.GetAccessKeyId()
 accessSecret, err := stsCredential.GetAccessKeySecret()
 securityToken, err := stsCredential.GetSecurityToken()
 credentialType := stsCredential.GetType()
 fmt.Println(accessKeyId, accessSecret, securityToken, credentialType)
}

Configure a RamRoleArn credential

You can assign a RAM role to automatically apply for and maintain an STS token. You can spcify a value for the Policy parameter to limit the permissions of an STS token.

import (
 "fmt"

 "github.com/aliyun/credentials-go/credentials"
)

func main(){
 config := new(credentials.Config).
  // Which type of credential you want
  SetType("ram_role_arn").
  // AccessKeyId of your account
  SetAccessKeyId("AccessKeyId").
  // AccessKeySecret of your account
  SetAccessKeySecret("AccessKeySecret").
  // Format: acs:ram::USER_Id:role/ROLE_NAME
  SetRoleArn("RoleArn").
  // Role Session Name
  SetRoleSessionName("RoleSessionName").
  // Not required, limit the permissions of STS Token
  SetPolicy("Policy").
  // Not required, limit the Valid time of STS Token
  SetRoleSessionExpiration(3600)

 arnCredential, err := credentials.NewCredential(config)
 if err != nil {
  return
 }
 accessKeyId, err := arnCredential.GetAccessKeyId()
 accessSecret, err := arnCredential.GetAccessKeySecret()
 securityToken, err := arnCredential.GetSecurityToken()
 credentialType := arnCredential.GetType()
 fmt.Println(accessKeyId, accessSecret, securityToken, credentialType)
}

Configure an EcsRamRole credential

You can assign a RAM role to automatically apply for and maintain an STS token.

import (
 "fmt"

 "github.com/aliyun/credentials-go/credentials"
)

func main(){
 config := new(credentials.Config).
  // Which type of credential you want
  SetType("ecs_ram_role").
  // `roleName` is optional. It will be retrieved automatically if not set. It is highly recommended to set it up to reduce requests
  SetRoleName("RoleName")

 ecsCredential, err := credentials.NewCredential(config)
 if err != nil {
  return
 }
 accessKeyId, err := ecsCredential.GetAccessKeyId()
 accessSecret, err := ecsCredential.GetAccessKeySecret()
 securityToken, err := ecsCredential.GetSecurityToken()
 credentialType := ecsCredential.GetType()
 fmt.Println(accessKeyId, accessSecret, securityToken, credentialType)
}

Configure an RSA key pair

You can specify a private key file and a public key ID to apply for and automatically maintain your AccessKey pair. This method is available only for the Alibaba Cloud Japan site.

import (
 "fmt"

 "github.com/aliyun/credentials-go/credentials"
)

func main(){
 config := new(credentials.Config).
  // Which type of credential you want
  SetType("rsa_key_pair").
  // The file path to store the PrivateKey
  SetPrivateKeyFile("PrivateKeyFile").
  // PublicKeyId of your account
  SetPublicKeyId("PublicKeyId")

 rsaCredential, err := credentials.NewCredential(config)
 if err != nil {
  return
 }
 accessKeyId, err := rsaCredential.GetAccessKeyId()
 accessSecret, err := rsaCredential.GetAccessKeySecret()
 securityToken, err := rsaCredential.GetSecurityToken()
 credentialType := rsaCredential.GetType()
 fmt.Println(accessKeyId, accessSecret, securityToken, credentialType)
}

Configure a bearer token

If Cloud Call Center (CCC) requires bearer tokens as credentials, you must apply for and maintain bearer tokens.

import (
 "fmt"

 "github.com/aliyun/credentials-go/credentials"
)

func main(){
 config := new(credentials.Config).
  // Which type of credential you want
  SetType("bearer").
  // BearerToken of your account
  SetBearerToken("BearerToken").
 config := &credentials.Config{

 bearerCredential, err := credentials.NewCredential(config)
 if err != nil {
  return
 }
 bearerToken := bearerCredential.GetBearerToken()
 credentialType := bearerCredential.GetType()
 fmt.Println(bearerToken, credentialType)
}

Use the default credential provider chain

If you pass a null value to NewCredential(), you can use the default credential provider chain to obtain credentials. The default provider chain searches for access credentials and uses the identified credentials in the following order:

1. Environment variables

The provider chain searches for credentials in environment variables. If you specify non-null values for the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, the provider chain uses the environment variables to create default credentials. If you do not specify non-null values for the environment variables, the provider chain loads the configuration file and searches for credentials.

2. Configuration file

If the default credential file is stored in the home directory of the user, the provider chain automatically creates a credential based on the specified type and name. The path for the default credential file is ~/.alibabacloud/credentials. In Windows, the path is C:\Users\USER_NAME\.alibabacloud\credentials. If the default credential file does not exist, an exception is thrown when the system fails to parse a credential. You can also use AlibabaCloud::load('/data/credentials', 'vfs://AlibabaCloud/credentials', ...); to load a specified file. The configuration file is stored outside projects and cannot be committed to public GitHub projects. Therefore, the configuration file can be used by different projects and tools at the same time. In Windows, you can use the environment variable %UserProfile% to reference your home directory. In Unix-like systems, you can use the environment variable $HOME or a tilde (~) to reference your home directory. You can configure the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable to change the path of the default credential file.

[default]                          # The default credential.
type = access_key                  # The authentication is based on AccessKey pairs.
access_key_id = foo                # access key id
access_key_secret = bar            # access key secret

3. Instance RAM role

If you specify a non-null value for the ALIBABA_CLOUD_ECS_METADATA environment variable, the provider chain uses the value of the environment variable as the role name, and then sends a request to http://100.100.100.200/latest/meta-data/ram/security-credentials/ to obtain temporary security credentials.