This topic describes how to configure credentials.
If you use an AccessKey pair as an access credential, you must configure the credential when you initialize an SDK client. This topic provides sample code on how to configure credentials.
Keep the code that contains your AccessKey pair confidential. For example, do not commit the code to public GitHub projects. If the code leaks, your Alibaba Cloud account may be compromised.
Use an AccessKey pair
The most common method is to use github.com/alibabacloud-go/darabonba-openapi/v2/client
to configure credentials. The following code provides an example:
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
facebody "github.com/alibabacloud-go/facebody-20191230/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/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-shanghai").
SetEndpoint("facebody.cn-shanghai.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.DetectFaceWithOptions(request, runtimeObject)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(resp)
}
You can also use the SDK Credentials package to configure credentials. This method is commonly used and supports multiple types of credentials. The following section describes how to use the SDK Credentials package to configure credentials.
Use the SDK Credentials package
Install the SDK Credentials package
Make sure that Go 1.10.x or a later version is installed on your system.
To obtain a good experience, we recommend that you use the latest version of credentials-go. Each version includes feature optimization and bug fixes from the previous version. For more information, see Releases.
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
You must have an Alibaba Cloud account and an AccessKey pair to use Alibaba Cloud 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 your Alibaba Cloud account. Keep your AccessKey pair confidential. For security reasons, we recommend that you do not share an AccessKey pair of your Alibaba Cloud account with a developer. Instead, you can create a RAM user and grant permissions to the RAM user. This way, the developer can use an AccessKey pair of the RAM user to call API operations.
// This file is auto-generated, don't edit it. Thanks.
package main
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("ACCESS_KEY_ID").
// AccessKeySecret of your account
SetAccessKeySecret("ACCESS_KEY_SECRET")
akCredential, err := credentials.NewCredential(config)
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 specify 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 automatically apply for and 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")
bearerCredential, err := credentials.NewCredential(config)
if err != nil {
return
}
bearerToken := bearerCredential.GetBearerToken()
credentialType := bearerCredential.GetType()
fmt.Println(bearerToken, credentialType)
}
Use a credential URI
You can specify a URI for credentials to obtain a credential and automatically apply for and maintain an STS token.
import (
"fmt"
"github.com/aliyun/credentials-go/credentials"
)
func main() {
config := new(credentials.Config).SetType("credentials_uri").SetURLCredential("http://local_or_remote_uri/")
credential, err := credentials.NewCredential(config)
if err != nil {
return
}
accessKeyId, err := credential.GetAccessKeyId()
accessKeySecret, err := credential.GetAccessKeySecret()
fmt.Println(accessKeyId, accessKeySecret)
}
Use the default credential provider chain
import (
"fmt"
openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
facebody20191230 "github.com/alibabacloud-go/facebody-20191230/v3/client"
util "github.com/alibabacloud-go/tea-utils/v2/service"
"github.com/alibabacloud-go/tea/tea"
"github.com/aliyun/credentials-go/credentials"
)
func main() {
defaultCredential, err := credentials.NewCredential(nil)
if err != nil {
return
}
config := &openapi.Config{Credential: defaultCredential}
config.Endpoint = tea.String("facebody.cn-shanghai.aliyuncs.com")
_client, _err := facebody20191230.NewClient(config)
if _err != nil {
return
}
listBodyPersonRequest := &facebody20191230.ListBodyPersonRequest{}
runtime := &util.RuntimeOptions{}
resp, _err := _client.ListBodyPersonWithOptions(listBodyPersonRequest, runtime)
if _err != nil {
return
}
fmt.Println(resp.Body.RequestId)
}
If you specify null for the NewCredential()
parameter, 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 credential provider chain searches for credentials in environment variables. If you define the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID
and ALIBABA_CLOUD_ACCESS_KEY_SECRET
and specify non-null values for the environment variables, the credential provider chain uses the environment variables to create credentials. If the version of credentials-go that you use is 1.2.3 or earlier, you need to define the environment variable ALIBABA_CLOUD_ACCESS_KEY_Id
instead of ALIBABA_CLOUD_ACCESS_KEY_ID. You can upgrade credentials-go to the latest version to ensure your development experience. If you specify null for the environment variables, the credential 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 credential 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 define the ALIBABA_CLOUD_ECS_METADATA
environment variable and specify a non-null value for the environment variable, the credential provider chain uses the value of the environment variable as the RAM role name and sends a request to http://100.100.100.200/latest/meta-data/ram/security-credentials/
to obtain temporary security credentials.