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.
Usage notes
If you want to obtain information about OSS regions and endpoints, see Regions and endpoints.
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 | AccessKey pair | 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 | Security 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 | Security 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 | Security token | Temporary | Automatic refresh | |
Untrusted applications are deployed and run on ACK worker nodes. | No | Security 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 | |
If you initialize a Credentials client without specifying an initialization method, the Credentials tool obtains credentials based on the order of the default credential provider chain. | Custom | Custom | Custom | Custom |
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.
For information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair for a RAM user. The AccessKey pair of a RAM user is displayed only when the RAM user is created. Save the AccessKey pair in a timely manner. If you forget the AccessKey pair, create a new AccessKey pair for rotation.
Configure environment variables for the AccessKey pair.
Linux
Run the following commands on the CLI to add the configurations of the environment variables to the
~/.bashrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc
Run the following command to apply the changes:
source ~/.bashrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
Run the following command in the terminal to view the default shell type:
echo $SHELL
Configure environment variables based on the default shell type.
Zsh
Run the following commands to add the configurations of the environment variables to the
~/.zshrc
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc
Run the following command to apply the changes:
source ~/.zshrc
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
Run the following commands to add the configurations of the environment variables to the
~/.bash_profile
file:echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile
Run the following command to apply the changes:
source ~/.bash_profile
Run the following commands to check whether the environment variables take effect:
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Windows
CMD
Run the following commands in CMD:
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET"
Run the following commands to check whether the environment variables take effect:
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
Run the following commands in PowerShell:
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Run the following commands to check whether the environment variable takes effect:
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
Pass credentials 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 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 OSSClient instance. 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 credentials 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 OSSClient instance. 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.
If you want to obtain information about STS endpoints, see Endpoints.
Use the temporary access credentials to specify environment variables.
Mac OS X/Linux/Unix
WarningNote that the temporary access credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS are used instead of the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user.
The AccessKey ID obtained from STS starts with STS. Example: STS.L4aBSCSJVMuKg5U1****.
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Windows
WarningNote that the temporary access credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS are used instead of the AccessKey pair (AccessKey ID and AccessKey secret) of the RAM user.
The AccessKey ID obtained from STS starts with STS. Example: STS.L4aBSCSJVMuKg5U1****.
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>
Pass credentials 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 OSSClient instance. 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 OSSClient instance. 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 OSSClient instance. 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 the 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 OSSClient instance. 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 OSSClient instance. 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 OSSClient instance. client := oss.NewClient(cfg) log.Printf("ossclient: %v", client) }
Method 7: Use the default credential provider chain
If you do not specify a method to initialize a Credentials client, the default credential provider chain is used. For more information, see Default credential provider chain.
package main
import (
"context"
"log"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
osscred "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
"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"
// If you set the parameter to nil, the default credential provider chain is used and the credentials are automatically obtained.
arnCredential, gerr := credentials.NewCredential(nil)
provider := osscred.CredentialsProviderFunc(func(ctx context.Context) (osscred.Credentials, error) {
if gerr != nil {
return osscred.Credentials{}, gerr
}
cred, err := arnCredential.GetCredential()
if err != nil {
return osscred.Credentials{}, err
}
return osscred.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 OSSClient instance.
client := oss.NewClient(cfg)
log.Printf("ossclient: %v", client)
}
FAQ
What do I do if I use the AccessKey pair of a RAM user instead of the temporary access credentials obtained from STS to initialize a credential provider?
When you use temporary access credentials (AccessKey ID, AccessKey secret, and security token) obtained from STS to initialize a credential provider, do not confuse the AccessKey ID returned by STS with the AccessKey ID of the RAM user. The AccessKey ID obtained from STS starts with STS. Example:
How do I view the AccessKey ID of a RAM user? Can I view the AccessKey secret of an old AccessKey pair?
To view the AccessKey ID of a RAM user, see View the information about AccessKey pairs of a RAM user.
The AccessKey secret of a RAM user is displayed only when the AccessKey pair is created. You cannot view the AccessKey pair at a later time. If you forget the AccessKey secret, you cannot retrieve the AccessKey secret. You can directly select a specific RAM user in the RAM console and create a new AccessKey pair for rotation. For more information, see Create an AccessKey pair.
If an error is reported, how do I determine the specific type of the error?
OSS provides Error codes to help you determine the specific type of an error. For example, see 02-AUTH for common authentication errors.