When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. Alibaba Cloud Credentials tool provides a powerful set of features that enable you to easily obtain and manage access credentials. This topic describes how to use the Credentials tool to configure various types of credentials such as the default credential, AccessKey pairs, or Security Token Service (STS) tokens. This topic also describes the order based on which the Credentials tool obtains the default credential. You can develop a thorough knowledge of configuring and managing credentials in Alibaba Cloud SDKs. This ensures that your operations on cloud resources are efficient and secure.
Background information
A credential is a set of information that is used to prove the identity of a user. When you log on to the system, you must use a valid credential to complete identity authentication. The following types of credentials are commonly used:
An AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid. It consists of an AccessKey ID and an AccessKey secret.
An STS token of a RAM role. An STS token is a temporary credential. You can specify a validity period and access permissions for an STS token. For more information, see What is STS?
A bearer token. It is used for identity authentication and authorization.
Prerequisites
.NET Framework 4.5 or later is installed.
.NET Standard 2.0 or later is installed.
C# 4.0 or later is installed.
Alibaba Cloud SDK V2.0 is installed.
The in-house SDKs of services that use self-managed gateways are not installed.
Install the Credentials tool
Run the following command on the .NET CLI to install Alibaba Cloud Credentials for .NET:
dotnet add package Aliyun.Credentials
Use the NuGet package manager to install Alibaba Cloud Credentials for .NET.
Right-click your project in the
Solution Explorer
panel and selectManage NuGet Packages
.On the
Browse
tab of theNuGet Package Manager
panel, enterAliyun.Credentials
in the search box in the upper-left corner.In the search results, select the package whose value of the
Authors
parameter isAlibaba Cloud
and click Install.
We recommend that you use the latest version of Alibaba Cloud Credentials for .NET.
For information about all released versions of Alibaba Cloud Credentials for .NET, see ChangeLog.md.
Initialize a Credentials client
You can use multiple methods to initialize a Credentials client. Use the Type
parameter to specify a method to initialize a Credentials client.
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 about how to obtain the default credential provider chain, see the Default credential provider chain section of this topic.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
// Do not specify a method to initialize a Credentials client.
Config config = new Config();
var credential = new Aliyun.Credentials.Client(config);
}
}
}
Call example
Use an AccessKey pair
You can create an AccessKey pair that is used to call API operations for your Alibaba Cloud account or a RAM user. For more information, see Create an AccessKey pair. Then, you can use the AccessKey pair to initialize a Credentials client.
An Alibaba Cloud account has full access to all resources of the account. AccessKey pair leaks of an Alibaba Cloud account pose critical threats to the system.
Therefore, we recommend that you use an AccessKey pair of a RAM user that is granted minimum necessary permissions to initialize a Credentials client.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "access_key",
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
};
var akCredential = new Aliyun.Credentials.Client(config);
string accessKeyId = akCredential.GetAccessKeyId();
string accessSecret = akCredential.GetAccessKeySecret();
string credentialType = akCredential.GetType();
}
}
}
Call example
Use an STS token
You can call the AssumeRole operation of STS as a RAM user to obtain an STS token. You can specify the maximum validity period of the STS token. The following sample code provides an example on how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.
{
"RequestId": "EA7A3526-F7DB-54A5-8300-9B742CFAA5EA",
"AssumedRoleUser": {
"Arn": "acs:ram::125499367423****:role/STStokenTestRole/STSsessionName",
"AssumedRoleId": "35219123109646****:STSsessionName"
},
"Credentials": {
"SecurityToken": "exampleToken",
"AccessKeyId": "STS.exampleAccessKeyID",
"AccessKeySecret": "exampleAccessKeySecret",
"Expiration": "2023-03-26T05:26:06Z"
}
}
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "sts",
// Replace <ALIBABA_CLOUD_ACCESS_KEY_ID> with the temporary AccessKey ID that is obtained from the response to the AssumeRole operation.
AccessKeyId = "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
// Replace <ALIBABA_CLOUD_ACCESS_KEY_SECRET> with the temporary AccessKey secret that is obtained from the response to the AssumeRole operation.
AccessKeySecret = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
// Replace <ALIBABA_CLOUD_SECURITY_TOKEN> with the STS token that is obtained from the response to the AssumeRole operation.
SecurityToken = "<ALIBABA_CLOUD_SECURITY_TOKEN>"
};
var stsCredential = new Aliyun.Credentials.Client(config);
string accessKeyId = stsCredential.GetAccessKeyId();
string accessSecret = stsCredential.GetAccessKeySecret();
string credentialType = stsCredential.GetType();
string securityToken = stsCredential.GetSecurityToken();
}
}
Call example
Use an AccessKey pair and a RAM role
The underlying logic of this method is to use an STS token to initialize a Credentials client. After you specify the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool can obtain an STS token from STS. You can also use the Policy
parameter to limit the permissions of the RAM role.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "ram_role_arn",
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// Specify the ARN of the RAM role to be assumed. Example: acs:ram::123456789012****:role/adminrole.
RoleArn = "<RoleArn>",
// Specify the name of the role session.
RoleSessionName = "<RoleSessionName>",
};
var arnCredential = new Aliyun.Credentials.Client(config);
string accessKeyId = arnCredential.GetAccessKeyId();
string accessSecret = arnCredential.GetAccessKeySecret();
string credentialType = arnCredential.GetType();
string securityToken = arnCredential.GetSecurityToken();
}
}
}
Call example
Use the RAM role of an ECS instance
The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool automatically obtains the RAM role attached to an ECS instance and uses the metadata server of ECS to obtain an STS token. The STS token is then used to initialize a Credentials client. You can also attach a RAM role to an elastic container instance or a worker node in an Alibaba Cloud Container Service for Kubernetes (ACK) cluster.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "ecs_ram_role",
// Optional. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
RoleName = "<RoleName>"
};
var ecsCredential = new Aliyun.Credentials.Client(config);
string accessKeyId = ecsCredential.GetAccessKeyId();
string accessSecret = ecsCredential.GetAccessKeySecret();
string credentialType = ecsCredential.GetType();
string securityToken = ecsCredential.GetSecurityToken();
}
}
}
Call example
Use a bearer token
Only Cloud Call Center allows you to use a bearer token to initialize a Credentials client.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "bearer",
// Enter the bearer token.
BearerToken = "<BearerToken>"
};
var bearerCredential = new Aliyun.Credentials.Client(config);
string bearerToken = bearerCredential.GetBearerToken();
string credentialType = bearerCredential.GetType();
}
}
}
Call example
Default credential provider chain
If you want to use different types of credentials in the development and production environments of your application, you generally need to obtain the environment information from the code and write code branches to obtain different credentials for the development and production environments. The default credential provider chain of the Credentials tool allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. If you use new Client(config)
to initialize a Credentials client without specifying an initialization method, the Credentials tool obtains the credential information in the following order:
1. Obtain the credential information from environment variables
The Credentials tool first obtains the credential information from environment variables. If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID) and ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret) system environment variables are specified, the Credentials tool uses the specified AccessKey pair as the default credential.
2. Obtain the credential information from a configuration file
If no credentials are found in the previous step, the Credentials tool obtains the credential information from a configuration file. The path of the configuration file varies based on the operating system:
Linux: ~/.alibabacloud/credentials
Windows: C:\Users\USER_NAME\.alibabacloud\credentials
You can also specify the configuration file path by configuring the ALIBABA_CLOUD_CREDENTIALS_FILE environment variable. If the configuration file exists, the application initializes a Credentials client by using the credential information that is specified by default in the configuration file. You can also configure the ALIBABA_CLOUD_PROFILE environment variable to modify the default credential information that is read.
[default]
type = access_key
access_key_id = foo
access_key_secret = bar
3. Obtain the credential information by using the RAM role of an ECS instance
If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_ECS_METADATA environment variable that specifies the RAM role name of an ECS instance. If the RAM role exists, the application obtains an STS token of the RAM role as the default credential by using the metadata server of ECS.
How to protect credential information
Credential leaks may expose the system to attacks. This is one of the main threats to cloud services. To prevent the leaks of plaintext credential information and reduce security risks, you can use the following solutions:
We recommend that you use the RAM role of an ECS instance or an STS token.
We recommend that you use the default credential provider chain and record the credential information in environment variables or a configuration file.
To use an explicit initialization method to initialize a Credentials client, we recommend that you use system properties or environment variables to record the credential information and obtain the credential information by using the
Environment.GetEnvironmentVariable
method.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "access_key",
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
};
var akCredential = new Aliyun.Credentials.Client(config);
string accessKeyId = akCredential.GetAccessKeyId();
string accessSecret = akCredential.GetAccessKeySecret();
string credentialType = akCredential.GetType();
}
}
}
How to switch between credentials
You can use the following methods to use different credentials to call different API operations in your application.
Use multiple Credentials clients
Initialize multiple Credentials clients to pass different credentials to different request clients.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config1 = new Config()
{
Type = "access_key",
AccessKeyId = "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
AccessKeySecret = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
};
var akCredential = new Aliyun.Credentials.Client(config1);
Config config2 = new Config()
{
Type = "access_key",
AccessKeyId = "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
AccessKeySecret = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
};
var akCredential = new Aliyun.Credentials.Client(config2);
}
}
}
Use the AuthUtils class
If you initialize a Credentials client by using the credential information recorded in a configuration file, you can use the auth_util.client_type
parameter to switch between different credentials.
[default]
enable=true
type=access_key
access_key_id=<ALIBABA_CLOUD_ACCESS_KEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
[client1]
enable=true
type=sts
access_key_id=<ACCESS_ALIBABA_CLOUD_ACCESS_KEY_IDKEY_ID>
access_key_secret=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>
security_token=<security_token>
[client2]
enable=true
type=ecs_ram_role
role_name=<ecs_ram_role_name>
Sample code:
using Aliyun.Credentials.Models;
using Aliyun.Credentials.Utils;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
// If you do not specify the clientType property of the AuthUtils class, default is used.
Config config = new Config();
// Switch to the client1 credential.
AuthUtils.ClientType = "client1";
Config config = new Config();
// Switch to the client2 credential.
AuthUtils.ClientType = "client2";
Config config = new Config();
}
}
}