To use Object Storage Service (OSS) SDK for Go to initiate a request, you must configure access credentials. Alibaba Cloud services use access credentials to verify identity information and access permissions. You can select different types of access credentials based on authentication and authorization requirements. This topic describes how to configure temporary access credentials and long-term access credentials.
Select an initialization method
Credential providers
OSS supports multiple methods to initialize a credential provider. You can select a suitable method based on the authentication and authorization requirements of your actual scenario.
Initialization method | Scenario | AccessKey pair or security token required | Underlying credential | Credential validity period | Credential rotation or refresh method |
Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks and need to access cloud services for a long period of time without frequent credential rotation. | Yes | AK | Long-term | Manual rotation | |
Applications are deployed and run in an untrusted environment, in which case you want to manage the credential validity and the resources that can be accessed. | Yes | STS Token | Temporary | Manual refresh | |
Applications need to be authorized to access cloud services. For example, you can use this method to allow cross-account access to OSS. | Yes | STS Token | Temporary | Automatic refresh | |
Applications are deployed and run on Elastic Compute Service (ECS) instances, elastic container instances, and Container Service for Kubernetes (ACK) worker nodes. | No | STS Token | Temporary | Automatic refresh | |
Untrusted applications are deployed and run on ACK worker nodes. | No | STS Token | Temporary | Automatic refresh | |
If none of the preceding methods meet your requirements, you can use a custom method to obtain access credentials. | Custom | Custom | Custom | Custom |
Method 1: Method 1: Use an AccessKey pair
If your application is deployed in a secure and stable environment that is not vulnerable to external attacks and requires long-term access to OSS, you can use an AccessKey pair of your Alibaba Cloud account or a RAM user to initialize a credential provider. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey.
Environment variables
An Alibaba Cloud account has full permissions on resources within the account. Leaks of the Alibaba Cloud account AccessKey pair pose critical security threats. Therefore, we recommend that you use the AccessKey pair of a RAM user that is granted the minimum necessary permissions to initialize a credential provider.
Use the AccessKey pair to specify environment variables.
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Pass credential information by using environment variables.
package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" // Obtain access credentials from environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. provider := credentials.NewEnvironmentVariableCredentialsProvider() // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Static credentials
You can define access credentials by using variables in your code. During the code execution, these variables are populated with actual credential values obtained from environment variables, configuration files, or other external locations.
The following procedure describes how to use a configuration file to provide credentials:
The go-ini
library needs to be installed. To install the go-ini library, run the following command:
go get -u github.com/go-ini/ini
Create a configuration file named
config.ini
.[credentials] alibaba_cloud_access_key_id = <ALIBABA_CLOUD_ACCESS_KEY_ID> alibaba_cloud_access_key_secret = <ALIBABA_CLOUD_ACCESS_KEY_SECRET>
Pass credential information by using the configuration file.
package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" "gopkg.in/ini.v1" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" // Read the configuration file. cfgFile, err := ini.Load("config.ini") if err != nil { log.Fatalf("Failed to load config file: %v", err) } // Obtain the configurations. accessKeyID := cfgFile.Section("oss").Key("alibaba_cloud_access_key_id").String() accessKeySecret := cfgFile.Section("oss").Key("alibaba_cloud_access_key_secret").String() // Create a credential provider. provider := credentials.NewStaticCredentialsProvider(accessKeyID, accessKeySecret) // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Method 2: Use a security token
If your application needs to access OSS temporarily, you can use temporary access credentials, which consist of an AccessKey pair and a security token, obtained from Security Token Service (STS). Take note that this method requires you to manually maintain a security token. This poses security risks and increases maintenance complexity. If you want to access OSS multiple times, you must manually refresh the security token. For more information about how to obtain a security token, see AssumeRole.
Use the temporary access credentials to specify environment variables.
Mac OS X/Linux/Unix
export OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>
Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>
Pass credential information by using environment variables.
package main import ( "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. provider := credentials.NewEnvironmentVariableCredentialsProvider() // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Method 3: Use RAMRoleARN
If you need to authorize your application to access OSS, for example, when your application requires access to OSS resources of another Alibaba Cloud account, you can use RAMRoleARN to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. By using the specified the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains a security token from STS and automatically refreshes the security token before the session expires. You can specify the Policy
parameter to limit the permissions granted to the RAM role. Take note that this method requires an AccessKey pair, which poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey. For more information about how to obtain the ARN of a RAM role, see CreateRole.
Add the credentials dependency.
go get github.com/aliyun/credentials-go/credentials
Configure access credentials.
package main import ( "context" "log" "os" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" config := new(openapicred.Config). // Set the credential type to ram_role_arn. SetType("ram_role_arn"). // Obtain the AccessKey ID and AccessKey secret of the RAM user from the environment variables. SetAccessKeyId(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")). SetAccessKeySecret(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")). // By default, the values of the parameters are directly entered for the following operations. You can also add environment variables and use os.Getenv("<variable name>") to specify the corresponding parameters. // Obtain the ARN of the RAM role from the environment variable, which is the ID of the RAM role to be assumed. Format: acs:ram::$accountID:role/$roleName. SetRoleArn("ALIBABA_CLOUD_ROLE_ARN"). // By default, the canonical name of the RoleArn environment variable is ALIBABA_CLOUD_ROLE_ARN. // Specify a custom session name for the role to distinguish different tokens. SetRoleSessionName("ALIBABA_CLOUD_ROLE_SESSION_NAME"). // By default, the canonical name of the RoleSessionName environment variable is ALIBABA_CLOUD_ROLE_SESSION_NAME. // Optional. Specify the permissions of the security token. SetPolicy("Policy"). // Optional. Specify the validity period of the security token. SetRoleSessionExpiration(3600) arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Method 4: Use ECSRAMRole
If your application runs on an ECS instance, an elastic container instance, or an ACK worker node, we recommend that you use ECSRAMRole to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. ECSRAMRole allows you to attach a RAM role to an ECS instance, an elastic container instance, or an ACK worker node to automatically refresh the security token on the instance. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information about how to obtain ECSRAMRole, see CreateRole.
Add the credentials dependency.
go get github.com/aliyun/credentials-go/credentials
Configure access credentials.
package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" config := new(openapicred.Config). // Set the credential type to ecs_ram_role. SetType("ecs_ram_role"). // Optional. Specify the role name. If you do not specify the role name, OSS automatically generates a role name. We recommend that you specify a role name to reduce the number of requests. SetRoleName("RoleName") arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Method 5: Use OIDCRoleARN
After the RAM role is configured on the ACK worker node, the application in a pod on the node can obtain the security token of the attached role by using the metadata server in the same manner as an application deployed on an ECS instance does. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is unavailable to you, you may not want the application to use the metadata server to obtain a security token of the RAM role attached to the worker node. To ensure the security of cloud resources, allow untrusted applications to securely obtain the required security token, and minimize application-level permissions, you can use the RAM Roles for Service Account (RRSA) feature. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information of environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the security token of attached roles. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information, see Use RRSA to authorize different pods to access different cloud services.
Add the credentials dependency.
go get github.com/aliyun/credentials-go/credentials
Configure access credentials.
package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" openapicred "github.com/aliyun/credentials-go/credentials" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" config := new(openapicred.Config). // Set the credential type to oidc_role_arn. SetType("oidc_role_arn"). // Specify the ARN of the OIDC IdP. The ARN is in the acs:ram::account-id:oidc-provider/provider-name format. SetOIDCProviderArn("OIDCProviderArn"). // Specify the path of the file in which the OIDC token is stored. SetOIDCTokenFilePath("OIDCTokenFilePath"). // Specify a custom session name for the role to distinguish different tokens. SetRoleSessionName("RoleSessionName"). // By default, the canonical name of the RoleSessionName environment variable is ALIBABA_CLOUD_ROLE_SESSION_NAME. // Optional. Specify the policy of the RAM role. SetPolicy("Policy"). // Specify the ARN of the RAM role, which is the ID of the RAM role to be assumed. Format: acs:ram::113511544585****:oidc-provider/TestOidcProvider. SetRoleArn("RoleArn"). // Specify the validity period of the session. SetSessionExpiration(3600) arnCredential, gerr := openapicred.NewCredential(config) provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { if gerr != nil { return credentials.Credentials{}, gerr } cred, err := arnCredential.GetCredential() if err != nil { return credentials.Credentials{}, err } return credentials.Credentials{ AccessKeyID: *cred.AccessKeyId, AccessKeySecret: *cred.AccessKeySecret, SecurityToken: *cred.SecurityToken, }, nil }) // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Method 6: Specify a custom credential provider
If the preceding credential configuration methods do not meet your business requirements, you can specify the method that you want to use to obtain access credentials. The following methods are supported:
Use the credentials.CredentialsProviderFunc method
package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" // Create a credential provider. provider := credentials.CredentialsProviderFunc(func(ctx context.Context) (credentials.Credentials, error) { // Return long-term credentials. return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret"}, nil // Return temporary credentials. //return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret", SecurityToken: "token"}, nil }) // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Use the credentials.CredentialsProvider method
package main import ( "context" "log" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" ) type CustomerCredentialsProvider struct { // TODO } func NewCustomerCredentialsProvider() CustomerCredentialsProvider { return CustomerCredentialsProvider{} } func (s CustomerCredentialsProvider) GetCredentials(_ context.Context) (credentials.Credentials, error) { // Return long-term credentials. return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret"}, nil // Return temporary credentials. //return credentials.Credentials{AccessKeyID: "id", AccessKeySecret: "secret", SecurityToken: "token"}, nil } func main() { // Specify the ID of the region in which the bucket is located based on your business requirements. For example, if the bucket is located in the China (Hangzhou) region, set the region ID to cn-hangzhou. region := "cn-hangzhou" // Create a credential provider. provider := NewCustomerCredentialsProvider() // Load the default configurations and specify the credential provider and region. cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(provider). WithRegion(region) // Create an OSS client. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }