When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. The Credentials tool of Alibaba Cloud provides a set of easy-to-use features and supports various types of credentials, including the default credential, AccessKey pairs, and Security Token Service (STS) tokens. The Credentials tool helps you obtain and manage credentials. This topic 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 you can perform operations on cloud resources in an efficient and secure manner.
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:
The AccessKey pair of an Alibaba Cloud account or a Resource Access Management (RAM) user. An AccessKey pair is permanently valid and 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.
Prerequisite
.NET Framework 4.5 or later.
.NET Standard 2.0 or later.
C# 4.0 or later.
Alibaba Cloud SDK V2.0 is 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.
In the
Solution Explorer panel
, right-click your project and selectManage NuGet Packages
.In the
NuGet management panel
that appears, click theBrowse
tab and enterAliyun.Credentials
.In the list below, select the package whose
Authors
isAlibaba Cloud
and click Install.
We recommend that you use the latest version of Alibaba Cloud Credentials for .NET. This ensures that all credentials are supported.
View ChangeLog.txt to obtain a list of all released versions.
Credentials tool configuration parameters
The configuration parameters of the Credentials tool are defined in Aliyun.Credentials.Models.Config
. The credential type is specified by the required parameter type
. After you determine the credential type, you need to select the corresponding parameters based on the credential type. The following table describes the valid values of type
and the parameters supported by each credential type. In the table, √
indicates a required parameter, -
indicates an optional parameter, and ×
indicates an unsupported parameter.
Credential types and parameters that are not listed in the following table are not recommended for use.
Type | access_key | sts | ram_role_arn | ecs_ram_role | oidc_role_arn | credentials_uri | bearer |
AccessKeyId: The access credential ID. | √ | √ | √ | × | × | × | × |
AccessKeySecret: The access credential secret. | √ | √ | √ | × | × | × | × |
SecurityToken: The STS token. | × | √ | - | × | × | × | × |
RoleArn: The ARN of the RAM role. | × | × | √ | × | √ | × | × |
RoleSessionName: The custom session name. The default format is | × | × | - | × | - | × | × |
RoleName: The name of the RAM role. | × | × | × | - | × | × | × |
DisableIMDSv1: Specifies whether to forcibly use the security hardening mode. Default value: | × | × | × | - | × | × | × |
BearerToken: The bearer token. | × | × | × | × | × | × | √ |
Policy: The custom permission policy. | × | × | - | × | - | × | × |
RoleSessionExpiration: The session expiration time. Default value: 3600 seconds. | × | × | - | × | - | × | × |
OidcProviderArn: The ARN of the OIDC IdP. | × | × | × | × | √ | × | × |
OidcTokenFilePath: The path of the OIDC token file. | × | × | × | × | √ | × | × |
ExternalId: The external ID of the role. The main function is to prevent the confused deputy problem. For more information, see Use ExternalId to prevent the confused deputy problem. | × | × | - | × | × | × | × |
CredentialsURI: The URI of the credential. | × | × | × | × | × | √ | × |
STSEndpoint: The endpoint of STS. Both VPC endpoints and public endpoints are supported. For more information about the valid values, see Service registration. Default value: | × | × | - | × | - | × | × |
Timeout: The read timeout period of HTTP requests. Default value: 5000 milliseconds. | × | × | - | - | - | - | × |
ConnectTimeout: The connection timeout period of HTTP requests. Default value: 10000 milliseconds. | × | × | - | - | - | - | × |
Initialization
You can use one of the following methods to initialize a Credentials client based on your business requirements:
If you use a plaintext AccessKey pair in a project, the AccessKey pair may be leaked due to improper permission management on the code repository. This may threaten the security of all resources within the account to which the AccessKey pair belongs. We recommend that you store the AccessKey pair in environment variables or configuration files.
We recommend that you build the Credentials client in single-instance mode. This mode not only enables the credential caching feature of the SDK, but also effectively prevents traffic control issues and waste of performance resources caused by multiple API calls.
Method 1: 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 the logic of the default credential provider chain, see Default credential provider chain.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
// Do not specify a value or specify null as the value.
var credential = new Aliyun.Credentials.Client();
// var credential = new Aliyun.Credentials.Client(null);
}
}
}
Sample code
Method 2: 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 permissions on resources within 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 permissions based on the principle of least privilege (PoLP) 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();
}
}
}
Sample code
Method 3: Use a Security Token Service (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 example shows how to initialize a Credentials client by using an STS token. The example does not show how to obtain an STS token.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "sts",
// Obtain the AccessKey ID from the environment variable.
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// Obtain the AccessKey secret from the environment variable.
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// Obtain the STS token from an environment variable.
SecurityToken = Environment.GetEnvironmentVariable("<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();
}
}
Sample code
Method 4: Use an AccessKey pair and a RAM role
The underlying logic of this method is to use an STS token. 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 limit the RAM role to a smaller set of permissions by specifying a value for Policy
.
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. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable.
RoleArn = "<RoleArn>",
// Specify the role session name. You can obtain the value from the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
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();
}
}
}
Sample code
Method 5: Use the RAM role of an ECS instance
ECS instances and elastic container instances can be assigned RAM roles. Programs that run on the instances can use the Credentials tool to automatically obtain an STS token for the RAM role. The STS token can be used to initialize the Credentials client.
By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2). If an exception occurs in the security hardening mode (IMDSv2), the Credentials tool obtains the access credential in normal mode. You can also specify the disableIMDSv1
parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to specify how to handle exceptions:
false (default): The Credentials tool continues to obtain the access credential in normal mode (IMDSv1).
true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode (IMDSv2).
The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2).
You can also configure the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable access to ECS metadata credentials.
To obtain a temporary identity credential in security hardening mode, make sure that the version of the Credentials tool is 1.4.2 or later.
For more information about instance metadata, see Instance metadata.
For more information about how to assign RAM roles to ECS instances and elastic container instances, see Create a RAM role and authorize an ECS instance to assume the role and Assign a RAM role to an elastic container instance.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
var 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. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable.
RoleName = "<RoleName>"
};
// Optional. Default value: false. true: The security hardening mode is forcibly used. false: The system preferentially attempts to obtain the access credential in security hardening mode (IMDSv2). If the attempt fails, the system switches to the normal mode (IMDSv1) to obtain access credentials
// config.DisableIMDSv1 = true;
var ecsCredential = new Aliyun.Credentials.Client(config);
string accessKeyId = ecsCredential.GetAccessKeyId();
string accessSecret = ecsCredential.GetAccessKeySecret();
string credentialType = ecsCredential.GetType();
string securityToken = ecsCredential.GetSecurityToken();
}
}
}
Sample code
Method 6: Use the RAM role of an OIDC IdP
After you attach a RAM role to a worker node in an Container Service for Kubernetes, applications in the pods on the worker node can use the metadata server to obtain an STS token the same way in which applications on ECS instances do. 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 not available to you, you may not want the application to use the metadata server to obtain an STS token of the RAM role attached to the worker node. To ensure the security of cloud resources and enable untrusted applications to securely obtain required STS tokens, you can use the RAM Roles for Service Accounts (RRSA) feature to grant permissions to an application based on the PoLP. In this case, the ACK cluster creates a service account OpenID Connect (OIDC) token file, associates the token file with a pod, and then injects relevant environment variables into the pod. Then, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS and obtains an STS token of the RAM role. For more information about the RRSA feature, see Use RRSA to authorize different pods to access different cloud services.
The following environment variables are injected into the pod:
ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC identity provider (IdP).
ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "oidc_role_arn",
// Specify the ARN of the RAM role by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
RoleArn = "<RoleArn>",
// Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
OIDCProviderArn = "<OidcProviderArn>",
// Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
OIDCTokenFilePath = "<OidcTokenFilePath>",
// Specify the role session name. You can do so by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
RoleSessionName = "<RoleSessionName>",
// (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
Policy = "<Policy>",
RoleSessionExpiration = 3600
};
var ecsCredential = new Aliyun.Credentials.Client(config);
}
}
}<code code-type="xCode" data-tag="codeblock" id="30768e6732qs8" outputclass="language-csharp">using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "oidc_role_arn",
// Specify the ARN of the RAM role by using the ALIBABA_CLOUD_ROLE_ARN environment variable.
RoleArn = "<RoleArn>",
// Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
OIDCProviderArn = "<OidcProviderArn>",
// Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
OIDCTokenFilePath = "<OidcTokenFilePath>",
// Specify the role session name. You can do so by using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
RoleSessionName = "<RoleSessionName>",
// (Optional) Specify limited permissions for the RAM role. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
Policy = "<Policy>",
RoleSessionExpiration = 3600
};
var ecsCredential = new Aliyun.Credentials.Client(config);
}
}
}
Sample code
Method 7: Use a credential URI
By encapsulating an STS token service within an application and providing a custom URI for external access, other services can obtain STS tokens only through this URI, which effectively reduces the risk of exposing information such as AccessKey pairs. The Credentials tool supports obtaining STS tokens by requesting this service's URI, thereby initializing the Credentials client.
using Aliyun.Credentials.Models;
namespace credentials_demo
{
class Program
{
static void Main(string[] args)
{
Config config = new Config()
{
Type = "credentials_uri",
// Specify the URI of the credential in the http://local_or_remote_uri/ format. You can obtain the value from the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
CredentialsURI = "<CredentialsURI>"
};
}
}
}
Sample code
Method 8: Use a bearer token
Currently, only the Cloud Call Center CCC product supports initializing credentials with a bearer token.
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();
}
}
}
Sample code
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 Alibaba Cloud Credentials for .NET allows you to use the same code to obtain credentials for different environments based on configurations independent of the application. When you initialize a Credentials client without specifying parameters by calling new Client(config)
and passing null
, Alibaba Cloud SDK attempts to find credential information in the following order.
1. Using environment variables
If no credential information is found in the system attributes, the Credentials continues to check the environment variables.
If both the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are specified, they are used as the default credential.
If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are specified, the STS token is used as the default credential.
2. Obtain the credential information by using the RAM role of an OIDC IdP
If no credentials with a higher priority are found, the Credentials tool checks the following environment variables that are related to the RAM role of the OIDC IdP:
ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC IdP.
ALIBABA_CLOUD_OIDC_TOKEN_FILE: the file path of the OIDC token.
If the preceding three environment variables are specified and valid, the Credentials tool uses the environment variables to call the AssumeRoleWithOIDC operation of STS to obtain an STS token as the default credential.
3. Obtain the credential information from the config.json configuration file
If no credentials with a higher priority are found, the Credentials tool attempts to load the config.json
file. Default file path:
Linux:
~/.aliyun/config.json
Windows:
C:\Users\USER_NAME\.aliyun\config.json
Do not change the preceding default paths. If you want to use this method to configure an access credential, manually create a config.json file in the corresponding path. Example:
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
},
{
"name":"client1",
"mode":"RamRoleArn",
"access_key_id":"<ALIBABA_CLOUD_ACCESS_KEY_ID>",
"access_key_secret":"<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"client2",
"mode":"EcsRamRole",
"ram_role_name":"<RAM_ROLE_ARN>"
},
{
"name":"client3",
"mode":"OIDC",
"oidc_provider_arn":"<OIDC_PROVIDER_ARN>",
"oidc_token_file":"<OIDC_TOKEN_FILE>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
},
{
"name":"client4",
"mode":"ChainableRamRoleArn",
"source_profile":"<PROFILE_NAME>",
"ram_role_arn":"<ROLE_ARN>",
"ram_session_name":"<ROLE_SESSION_NAME>",
"expired_seconds":3600
}
]
}
In the config.json file, you can use mode to specify a type of credential:
AK: uses the AccessKey pair of a RAM user to obtain the credential information.
RamRoleArn: uses the ARN of a RAM role to obtain the credential information.
EcsRamRole: uses the RAM role attached to an ECS instance to obtain the credential information.
OIDC: uses the ARN of an OIDC IdP and the OIDC token file to obtain the credential information.
ChainableRamRoleArn: uses a role chain and specifies an access credential in another JSON file to obtain the credential information.
Configure other parameters based on your business requirements.
After you complete the configurations, the Credentials tool selects the credential specified by the current parameter in the configuration file and initialize the client. You can also specify the ALIBABA_CLOUD_PROFILE environment variable to specify the credential information. For example, you can set the ALIBABA_CLOUD_PROFILE environment variable to client1.
4. Obtain the credential information by using the RAM role of an ECS instance
If no credentials with a higher priority are found, the Credentials tool attempts to use the RAM role assigned to the ECS instance to obtain a credential. By default, the Credentials tool accesses the metadata server of ECS in security hardening mode (IMDSv2) to obtain the STS token of the RAM role used by the ECS instance and uses the STS token as the default credential. The Credentials tool automatically accesses the metadata server of ECS to obtain the name of the RAM role (RoleName) and then obtains the credential. Two requests are sent in this process. If you want to send only one request, add the ALIBABA_CLOUD_ECS_METADATA environment variable to specify the name of the RAM role. If an exception occurs in the security hardening mode (IMDSv2), the Credentials tool obtains the access credential in normal mode (IMDSv1). You can also configure the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable to specify an exception handling logic. Valid values:
false: The Credentials tool continues to obtain the access credential in normal mode (IMDSv1).
true: The exception is thrown and the Credentials tool continues to obtain the access credential in security hardening mode.
The configurations for the metadata server determine whether the server supports the security hardening mode (IMDSv2).
In addition, you can specify ALIBABA_CLOUD_ECS_METADATA_DISABLED=true to disable access from the Credentials tool to the metadata server of ECS.
For more information about ECS instance metadata, see Obtain instance metadata.
For more information about how to attach a RAM role to an ECS instance, see the "Create an instance RAM role and attach the instance RAM role to an ECS instance" section of the Instance RAM roles topic. For more information about how to attach a RAM role to an elastic container instance, see the "Assign the instance RAM role to an elastic container instance" section of the Use an instance RAM role by calling API operations topic.
5. Obtain the credential information based on a URI
If no valid credential is obtained by using the preceding methods, the Credentials tool checks the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this environment variable exists and specifies a valid URI, the Credentials tool initiates an HTTP requests to obtain an STS token as the default credential.
Automatic update mechanism for session credentials
Session credentials include ARNs of RAM roles (RamRoleArn), RAM roles of ECS instances, RAM roles of OIDC IdPs (OIDCRoleArn), and credential URIs. The Credentials tool provides a built-in automatic update mechanism for session credentials. After a credential is obtained from the first call, the Credentials tool stores the credential in the cache. In subsequent calls, the credential is read from the cache as long as the credential is not expired. Otherwise, the Credentials tool makes a call to obtain the credential again, and updates the credential in the cache.
For RAM roles of ECS instances, the Credentials tool updates the credential 15 minutes before the cache time-to-live (TTL) ends.
The following example shows how to create a Credentials client by using the singleton pattern and use the Credentials client to initialize a cloud service client. Then, the example shows how to call API operations at different time intervals to verify whether the internal cache is used and whether the credential is refreshed after the cache expires.
using System;
using System.Threading.Tasks;
using Aliyun.Credentials.Models;
using AlibabaCloud.SDK.Ecs20140526;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.TeaUtil.Models;
namespace Example
{
/// <summary>
/// Credential class is used to manage Alibaba Cloud credential instances and uses a static singleton pattern.
/// </summary>
public static class Credential
{
private static readonly Lazy<Aliyun.Credentials.Client> _instance = new(() =>
{
try
{
var config = new Aliyun.Credentials.Models.Config
{
Type = "ram_role_arn",
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
RoleArn = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ROLE_ARN"),
RoleSessionName = "RamRoleArnTest",
RoleSessionExpiration = 3600
};
return new Aliyun.Credentials.Client(config);
}
catch (Exception ex)
{
throw new InvalidOperationException("Credential initialization failed: " + ex.Message, ex);
}
});
public static Aliyun.Credentials.Client Instance => _instance.Value;
}
/// <summary>
/// EcsClient class is used to manage ECS client instances and uses a static singleton pattern.
/// The endpoint and credential must be set through Initialize.
/// </summary>
public static class EcsClient
{
private static string _endpoint = string.Empty; // Explicitly initialized, cannot be null
private static Aliyun.Credentials.Client _credential = null!; // Explicitly initialized, cannot be null
private static readonly Lazy<AlibabaCloud.SDK.Ecs20140526.Client> _instance = new(() =>
{
if (string.IsNullOrEmpty(_endpoint))
{
throw new InvalidOperationException("Endpoint must be set before initializing the ECS client.");
}
if (_credential == null)
{
throw new InvalidOperationException("Credential must be set before initializing the ECS client.");
}
try
{
var ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config
{
Endpoint = _endpoint,
Credential = _credential
};
return new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
}
catch (Exception ex)
{
throw new InvalidOperationException("ECS client initialization failed: " + ex.Message, ex);
}
});
public static void Initialize(string endpoint, Aliyun.Credentials.Client credential)
{
if (string.IsNullOrEmpty(endpoint))
{
throw new ArgumentException("Endpoint cannot be null or empty.", nameof(endpoint));
}
if (credential == null)
{
throw new ArgumentNullException(nameof(credential), "Credential cannot be null.");
}
_endpoint = endpoint;
_credential = credential;
}
public static AlibabaCloud.SDK.Ecs20140526.Client Instance => _instance.Value;
}
public class Program
{
public static async Task Main(string[] args)
{
// Initialize EcsClient
EcsClient.Initialize("ecs.cn-hangzhou.aliyuncs.com", Credential.Instance);
Action task = () =>
{
try
{
var credential = Credential.Instance.GetCredential();
Console.WriteLine(DateTime.Now);
Console.WriteLine($"AK ID: {credential.AccessKeyId}, AK Secret: {credential.AccessKeySecret}, STS Token: {credential.SecurityToken}");
var ecsClient = EcsClient.Instance;
var request = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
var response = ecsClient.DescribeRegionsWithOptions(request, runtime);
Console.WriteLine($"Invoke result: {response.StatusCode}");
}
catch (Exception ex)
{
Console.WriteLine($"ECS client execution failed: {ex.Message}");
}
};
// Execute immediately
task();
// Start asynchronous tasks concurrently
var tasks = new[]
{
ScheduleTaskAsync(task, 600),
ScheduleTaskAsync(task, 4200),
ScheduleTaskAsync(task, 4300)
};
await Task.WhenAll(tasks);
Console.WriteLine("All tasks completed.");
}
private static async Task ScheduleTaskAsync(Action task, int delaySeconds)
{
await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
task();
}
}
}
Based on the log results, the following analysis can be made:
During the first call, since no credential information is cached, the system obtains credential information based on the configuration. After the credential is obtained, it is saved in the cache.
The credential information used in the second call is the same as that in the first call, indicating that the credential information for the second call is retrieved from the cache.
During the third call, since the credential's expiration time (RoleSessionExpiration) is set to 3600 seconds and the third call occurs 4200 seconds after the first call, the credential in the cache has expired. Therefore, the SDK automatically refreshes the credential based on the automatic update mechanism, obtains a new credential, and saves the new credential in the cache.
The credential information used in the fourth call is consistent with the newly obtained credential information from the third call, indicating that the credential in the cache has been updated to the new credential after expiration.