Managing access credentials

更新时间:
复制 MD 格式

The Alibaba Cloud SDK uses the Credentials tool to centrally manage credentials, such as your AccessKey and STS Token. This topic describes the supported credential types and their configuration methods.

Prerequisites

  • .NET Framework 4.5 or later.

  • .NET Standard 2.0 or later.

  • C# 4.0 or later.

  • Alibaba Cloud SDK for .NET V2.0 or later.

Install the credentials tool

If you have already installed Alibaba Cloud Credentials for .NET, you can skip this step. Use the latest version of the credentials package to ensure support for all credential types. For information about all released versions, see ChangeLog.md.

You can install Alibaba Cloud Credentials for .NET in one of the following ways:

  • Install the package with the .NET CLI.

    dotnet add package Aliyun.Credentials
  • Install the package with the NuGet package manager.

    1. Right-click your project in Solution Explorer and select Manage NuGet Packages.

    2. In NuGet Package Manager, click the Browse tab and enter Aliyun.Credentials.

    3. From the list, select the official package where the Authors is Alibaba Cloud, and click Install.

After the installation is complete, run the following command. The output lists Aliyun.Credentials and its version number:

dotnet list package

Parameters for the credential tool

The configuration parameters for the credential tool are defined in Aliyun.Credentials.Models.Config. The required type parameter specifies the credential type. After selecting a credential type, configure its corresponding parameters. The following table details the valid values for 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.

Note

Use only the credential types and parameters listed in the following table.

Type

access_key

sts

ram_role_arn

ecs_ram_role

oidc_role_arn

credentials_uri

bearer

AccessKeyId: The Access Key ID.

×

×

×

×

AccessKeySecret: The Access Key Secret.

×

×

×

×

SecurityToken: The security token.

×

-

×

×

×

×

RoleArn: The ARN of the RAM role.

×

×

×

×

×

RoleSessionName: The name of the custom session. The default format is credentials-csharp-<timestamp>.

×

×

-

×

-

×

×

RoleName: The name of the RAM role.

×

×

×

-

×

×

×

DisableIMDSv1: Specifies whether to disable IMDSv1 to enforce security hardening mode (IMDSv2). The default value is false.

×

×

×

-

×

×

×

BearerToken: The bearer token.

×

×

×

×

×

×

Policy: A custom policy.

×

×

-

×

-

×

×

RoleSessionExpiration: The session timeout period, in seconds. The default value is 3600.

×

×

-

×

-

×

×

OidcProviderArn: The ARN of the OIDC identity provider.

×

×

×

×

×

×

OidcTokenFilePath: The file path to the OIDC token.

×

×

×

×

×

×

ExternalId: An external ID used to prevent the confused deputy problem. For more information, see Use an external ID to prevent the confused deputy problem.

×

×

-

×

×

×

×

CredentialsURI: The URI of the credential.

×

×

×

×

×

×

STSEndpoint: The endpoint of STS. Both VPC and public endpoints are supported. For a list of valid values, see Endpoints. The default value is sts.aliyuncs.com.

×

×

-

×

-

×

×

Timeout: The read timeout for HTTP requests, in milliseconds. The default value is 5000.

×

×

-

-

-

-

×

ConnectTimeout: The connection timeout for HTTP requests, in milliseconds. The default value is 10000.

×

×

-

-

-

-

×

Initialize credentials client

The previous section describes the credential types and configuration parameters supported by the Credentials tool. The following sections provide code examples showing how to use the tool. Select the method that best fits your scenario.

Important
  • Hard-coding an AccessKey in your project creates security risks. Improperly managed repository permissions can expose all resources in your account. It is recommended to store the AccessKey in environment variables or configuration files.

  • Use a singleton pattern with the Credentials tool. This pattern enables the tool's built-in credential caching to prevent rate limiting from frequent API calls and avoid resource waste from creating multiple instances. For more information, see Automatic refresh of session credentials.

Method 1: Default credential provider chain

If you initialize a Credentials client without any parameters, the Credentials tool uses the default credential provider chain. To learn how the SDK loads default credentials, see Default credential provider chain.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Pass no parameters, or pass null.
            var credential = new Aliyun.Credentials.Client();
            // var credential = new Aliyun.Credentials.Client(null);
        }
    }
}

API call example

This example shows how to call the DescribeRegions operation of ECS. Install the ECS SDK before running the code.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the Credentials client by using the default credential provider chain.
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(null);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the service endpoint. This example uses the China (Beijing) region.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request object for the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and get the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 2: AccessKey

The Credentials tool uses the AccessKey you provide as the access credential.

Warning

An Alibaba Cloud account (root account) has full permissions over all its resources, so an exposed AK poses a significant security risk. Do not use the AK of a root account.

Use the AK of a RAM user with least-privilege permissions.

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();
        }
    }
}

API example

This example calls the DescribeRegions operation of ECS. Before running the code, install the ECS SDK.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Use an AccessKey pair to initialize the Credentials client.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "access_key",
                // Obtain the AccessKey ID from an environment variable.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Obtain the AccessKey Secret from an environment variable.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Specify the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = ecsClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 3: Use an STS token

The Credentials tool uses the static STS token you provide as the access credential.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "sts", 
                // Get the AccessKey ID from an environment variable.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Get the AccessKey Secret from an environment variable.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), 
                // Get the security 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();
        }
    }

API call example

This example shows how to call the DescribeRegions operation of ECS. Before you run the code, you must install the ECS SDK and the STS SDK.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the Credentials client with STS credentials.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "sts", 
                // Get the AccessKey ID from an environment variable.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Get the AccessKey Secret from an environment variable.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"), 
                // Get the temporary SecurityToken from an environment variable.
              	SecurityToken = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN")
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client ecsClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = ecsClient.DescribeRegionsWithOptions(describeRegionsRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 4: Access key and RAM role ARN

This method uses an STS token internally. When you specify the ARN (Alibaba Cloud Resource Name) of a RAM role, the credentials tool obtains an STS token from STS. You can also use the Policy parameter to apply a smaller permission set to 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"),
              	// The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can also set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",  
              	// The role session name. You can also set this using 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();
        }
    }
}

API call

This example shows how to call the DescribeRegions operation in ECS. You must install the ECS SDK before running the code.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the Credentials client with an AccessKey pair and a RAM role ARN.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "ram_role_arn",
                // Specify your AccessKey ID.
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Specify your AccessKey Secret.
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // The role session name. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>",
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Set the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation to get the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 5: ECS instance RAM role

You can attach an instance RAM role to ECS and ECI instances, allowing applications on the instances to use the Credentials tool to automatically retrieve the role's STS token to initialize a credentials client.

By default, the Credentials tool uses security hardening mode (IMDSv2) to access the ECS metadata server. If an error occurs, the tool falls back to normal mode to retrieve the access credential. You can configure this fallback behavior by setting the disableIMDSv1 parameter or the ALIBABA_CLOUD_IMDSV1_DISABLE environment variable:

  • If the value is false (default), the tool continues to retrieve the access credential in normal mode.

  • If the value is true, the tool uses only security hardening mode. If the retrieval fails, it throws an exception.

Support for IMDSv2 depends on the server configuration.

You can also set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable to disable credential retrieval from ECS instance metadata.

Note
using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new Config()
            {
                Type = "ecs_ram_role",
              	// Optional. The ECS RAM role name. Specify this parameter to reduce the number of requests. If omitted, the system automatically retrieves the role name. You can also set the role name by using the ALIBABA_CLOUD_ECS_METADATA environment variable.
                RoleName = "<RoleName>" 
            };
            // Optional. Default: false. Set to true to enforce security hardening mode. If false, the system first attempts to retrieve the access credentials in security hardening mode and falls back to normal mode (IMDSv1) on failure.
            // 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();
        }
    }
}

API example

This example shows how to call the ECS DescribeRegions operation. Before running the code, install the ECS SDK for .NET.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client using the RAM role of an ECS instance.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "ecs_ram_role",
              	// Optional. The name of the RAM role for the ECS instance. If you omit this parameter, the system automatically retrieves the role name. Specifying this parameter reduces requests. You can also set the role name with the ALIBABA_CLOUD_ECS_METADATA environment variable.
                RoleName = "<RoleName>"
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize the DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 6: Using OIDCRoleArn

If you use OIDC for authentication and have created a RAM role for an OIDC identity provider, you can provide the OIDC provider ARN, OIDC token file path, and RAM role ARN to the Credentials tool. The tool then automatically calls the AssumeRoleWithOIDC API to obtain an STS token for the RAM role, which is used as the access credential. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials. For example, if your application runs in a Container Service for Kubernetes (ACK) cluster with RRSA enabled, the Credentials tool can read the OIDC configuration from the pod's environment variables and call the AssumeRoleWithOIDC API to obtain an STS token. You can then use this STS token to access Alibaba Cloud services.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "oidc_role_arn",
                // The ARN of the RAM role to assume. Set with the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // The ARN of the OIDC IdP. Set with the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                OIDCProviderArn = "<OidcProviderArn>",
                // The path of the OIDC token file. Set with the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                OIDCTokenFilePath = "<OidcTokenFilePath>",
                // The role session name. Set with the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>",
                // Optional. A custom policy that limits the permissions for the role session. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                Policy = "<Policy>",
                RoleSessionExpiration = 3600
            };
            var ecsCredential = new Aliyun.Credentials.Client(config);
        }
    }
}

API example

This example shows how to call the ECS DescribeRegions operation. To run this example, install the ECS SDK for .NET.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client with an OIDC role ARN.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The type of credential.
                Type = "oidc_role_arn",
                // The ARN of the RAM role to assume. You can set this using the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // The ARN of the OIDC provider. You can set this using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                OIDCProviderArn = "<OidcProviderArn>",
                // The path to the OIDC token file. You can set this using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                OIDCTokenFilePath = "<OidcTokenFilePath>",
                // The name for the role session. You can set this using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
                RoleSessionName = "<RoleSessionName>",
                // Optional. Specify a more restrictive policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
                Policy = "<Policy>",
                RoleSessionExpiration = 3600
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the service endpoint.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 7: Credential URI

You can encapsulate the Security Token Service (STS) behind a service URI, allowing external services to obtain an STS token without exposing sensitive information like AKs. The Credentials tool can then use this URI to fetch an STS token to use as the access credential. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials.

using Aliyun.Credentials.Models;
namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Config config = new Config()
            {
                Type = "credentials_uri",
              	// Specifies the URI for fetching the credential, e.g., http://local_or_remote_uri/. Alternatively, set the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
                CredentialsURI = "<CredentialsURI>"     
            };
        }
    }
}

API example

This example shows how to call the ECS DescribeRegions operation. Install the ECS SDK before running the code.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client using a URI.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "credentials_uri",
              	// The URI used to retrieve credentials, in `http://local_or_remote_uri/` format. The SDK also reads the URI from the `ALIBABA_CLOUD_CREDENTIALS_URI` environment variable.
                CredentialsURI = "<CredentialsURI>" 
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Configure the service endpoint. This example uses the China (Beijing) region.
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Configure the credential.
            ecsConfig.Credential = credentialClient;
            // Initialize the ECS client.
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a DescribeRegions request.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeRegionsRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configuration.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Calls the DescribeRegions operation and stores the response.
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeRegionsRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 8: Bearer token

Only Cloud Call Center (CCC) 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 your Bearer Token.
                BearerToken = "<BearerToken>"      
            };
            var bearerCredential = new Aliyun.Credentials.Client(config);
            string bearerToken = bearerCredential.GetBearerToken();
            string credentialType = bearerCredential.GetType();
        }
    }
}

API example

This example demonstrates how to call the GetInstance operation for Cloud Call Center. You must install the CCC SDK before running the code.

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;
namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Initialize the credential client with a bearer token.
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // The credential type.
                Type = "bearer",
                // Specify your bearer token.
                BearerToken = "<BearerToken>"
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);
            AlibabaCloud.OpenApiClient.Models.Config cccConfig = new AlibabaCloud.OpenApiClient.Models.Config()
            {
                // Configure the endpoint.
                Endpoint = "ccc.cn-shanghai.aliyuncs.com",
                // Set the credential object for authentication.
                Credential = credentialClient
            };
            // Initialize the CCC client.
            AlibabaCloud.SDK.CCC20200701.Client cccClient = new AlibabaCloud.SDK.CCC20200701.Client(cccConfig);
            // Initialize a GetInstance request.
            AlibabaCloud.SDK.CCC20200701.Models.GetInstanceRequest getInstanceRequest = new AlibabaCloud.SDK.CCC20200701.Models.GetInstanceRequest
            {
                InstanceId = "ccc-test",
            };
            // Initialize runtime options.
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the GetInstance operation.
            AlibabaCloud.SDK.CCC20200701.Models.GetInstanceResponse response = cccClient.GetInstanceWithOptions(getInstanceRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Default credential provider chain

When your application uses different credentials for its development and production environments, developers typically write conditional code to load the correct set for each environment. The default credential provider chain lets you use the same code and manage credentials for different environments through external configuration. When you initialize a credentials client by calling new Client(config) with no parameters or with null, the Alibaba Cloud SDK attempts to find credentials in the following order.

1. Using environment variables

If no credential is found in the system properties, the provider chain then checks for environment variables.

  • If both ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are present and not empty, the provider chain uses them as the default credential.

  • If ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are also set, the provider chain uses an STS token as the default credential.

2. Use an OIDC RAM role

If no credential has been found, the provider chain checks for the following environment variables related to an OIDC RAM role:

  • ALIBABA_CLOUD_ROLE_ARN: The ARN of the RAM role.

  • ALIBABA_CLOUD_OIDC_PROVIDER_ARN: The ARN of the OIDC provider.

  • ALIBABA_CLOUD_OIDC_TOKEN_FILE: The file path of the OIDC token.

If all three environment variables are present and not empty, the provider chain uses these values to call the AssumeRoleWithOIDC API of the Security Token Service (STS) to obtain an STS token.

3. Using config.json

If no credential has been found, the provider chain attempts to load the shared credentials file, config.json, from its default location and uses the credential specified in the file.

  • Linux/macOS: ~/.aliyun/config.json

  • Windows: C:\Users\USER_NAME\.aliyun\config.json

To configure a credential this way, you can use the Alibaba Cloud CLI or manually create a config.json file in the appropriate path. The following example shows the content format:

{
  "current": "<PROFILE_NAME>",
  "profiles": [
    {
      "name": "<PROFILE_NAME>",
      "mode": "AK",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>"
    },
    {
      "name": "<PROFILE_NAME1>",
      "mode": "StsToken",
      "access_key_id": "<ALIBABA_CLOUD_ACCESS_KEY_ID>",
      "access_key_secret": "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>",
      "sts_token": "<SECURITY_TOKEN>"
    },
    {
      "name":"<PROFILE_NAME2>",
      "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":"<PROFILE_NAME3>",
      "mode":"EcsRamRole",
      "ram_role_name":"<RAM_ROLE_ARN>"
    },
    {
      "name":"<PROFILE_NAME4>",
      "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":"<PROFILE_NAME5>",
      "mode":"ChainableRamRoleArn",
      "source_profile":"<PROFILE_NAME>",
      "ram_role_arn":"<ROLE_ARN>",
      "ram_session_name":"<ROLE_SESSION_NAME>",
      "expired_seconds":3600
    }
  ]
}

Parameter

Description

current

Specify the credential name to retrieve the corresponding credential configuration. The credential name is the value of the name parameter in profiles. By default, the system gives priority to the credential name specified by the ALIBABA_CLOUD_PROFILE environment variable. If this environment variable is not configured, the system uses the credential name specified by current.

profiles

Contains a collection of credential configurations. The mode parameter specifies the type of credential:

  • AK: Uses a RAM user's AccessKey as the credential.

  • StsToken: Uses an STS token as the credential.

  • RamRoleArn: Assumes a RAM role by using a RAM user's credentials to obtain a temporary credential.

  • EcsRamRole: Obtains a credential from instance metadata.

  • OIDC: Obtains a credential by using an OIDC provider ARN, an OIDC token, and a RAM role ARN.

  • ChainableRamRoleArn: Uses role chaining to obtain a new credential, using an initial credential from profiles that is specified by the source_profile parameter.

4. ECS instance RAM role

If your application runs on an Elastic Compute Service (ECS) or Elastic Container Instance (ECI) instance with an assigned RAM role, the Credentials tool retrieves an STS token from the instance metadata to use as the access credential. When accessing instance metadata, the tool first retrieves the name of the RAM role assigned to the instance. You can specify the RAM role name by using the roleName parameter or the ALIBABA_CLOUD_ECS_METADATA environment variable to reduce retrieval time and improve efficiency. Credentials obtained this way support automatic refresh. For more information, see Automatic refresh of session credentials.

  • If set to false (default), the tool falls back to normal mode to retrieve the credential.

  • If set to true, the tool only uses secured mode and throws an exception if access fails.

Whether your server supports IMDSv2 depends on its configuration.

To disable credential access from instance metadata, set the ALIBABA_CLOUD_ECS_METADATA_DISABLED=true environment variable.

Note

5. Credentials tool URI

If no credential has been found, the provider chain checks for the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. If this variable is set and points to a valid URI, the chain accesses the URI to retrieve an STS token.

Automatic refresh of session credentials

Session credential types, such as ram_role_arn, ecs_ram_role, oidc_role_arn, and credentials_uri, support automatic refresh through a built-in mechanism in the credential provider. When a credential client retrieves a credential for the first time, the provider stores it in a cache. In subsequent operations, the same client instance automatically retrieves the credential from this cache. If the cached credential has expired, the client instance fetches a new one and updates the cache accordingly.

Note

For ecs_ram_role credentials, the credential provider proactively refreshes them 15 minutes before they expire.

The following example uses the singleton pattern to create a credential client. It demonstrates the refresh mechanism by fetching a credential at different time intervals and calling an OpenAPI operation to verify that the credential is usable.

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>
    /// The Credential class manages the Alibaba Cloud credential instance by using the 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>
    /// The EcsClient class manages the ECS client instance by using the static singleton pattern.
    /// You must set the endpoint and credential by using Initialize.
    /// </summary>
    public static class EcsClient
    {
        private static string _endpoint = string.Empty; // Explicitly initialize. The value cannot be null.
        private static Aliyun.Credentials.Client _credential = null!; // Explicitly initialize. The value 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 the 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}");
                }
            };
            // Run the task 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();
        }
    }
}
2025/5/29 10:33:24
AK ID: STS.NVR3xxx P8KrfgTK, AK Secret: 6hsZk211xxx
        PeZZ8NHSBeQo, STS Token: CAISxAJ1q6Ft5B2yf5jIr5XneN+ChrwS1It+pcEXr0DkFNMReiaL/qTz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtBkQt5I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     JlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAsg    3PjcmYvy1dKzlhvI856BxNHBq+A748VMgj01iX9IIPPtJO3TwsQdpz0agaAFJZJGZS4RxwNkWL934H/nip/ameLEvxylbsU0x8]AMGRtHmlzYuolmGovqyeKhpDOT+H0am7tG2LvzKHoyVN8Kuck/qb/JAX/
xV1mHcLp3iPma8q+9xboP81YeU06c0vy   bzA2n7QI37852WyAA
Invoke result: 200
2025/5/29 10:43:25
AK ID: STS.NVR3xxx P8KrfgTK, AK Secret: 6hsZk211xxx
        PeZZ8NHSBeQo, STS Token: CAISxAJ1q6Ft5B2yf5jIr5XneN+ChrwS1It+pcEXr0DkFNMReiaL/qTz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtBkQt5I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     JlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAsg    3PjcmYvy1dKzlhvI856BxNHBq+A748VMgj01iX9IIPPtJO3TwsQdpz0agaAFJZJGZS4RxwNkWL934H/nip/ameLEvxylbsU0x8]AMGRtHmlzYuolmGovqyeKhpDOT+H0am7tG2LvzKHoyVN8Kuck/qb/JAX/
xV1mHcLp3iPma8q+9xboP81YeU06c0vy   bzA2n7QI37852WyAA
Invoke result: 200
2025/5/29 11:43:25
AK ID: STS.NWuFxxx BwvauFkU, AK Secret: 6fBbjmvd2T
        ChJTi9gPixZE, STS Token: CAISxAJ1q6Ft5B2yf5jIrSTAG/74uLB13aeARFwQlYXe/lNmoPAtzz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtdxAt7I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     iJlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAtQ    JU1tKDlwTxgBGOFKIQQrKj9PMSqhAcLJtS6MDE7NJKbt10KxV8Qdpz0agaAE7zrIhzsIKFMhIAyquB0Z8/YXeYdmswQUMbqmr+0gX306/0U9iWS612r6AalQSomcAD0eijKFnE8PFyx3YifekzIBCjr17TR
ujPRXpMzvxuXfvzz9eszDB0o0AXX5gTQ    IKDI4Y7necJANrPiAA
Invoke result: 200
2025/5/29 11:45:05
AK ID: STS.NWuPxxx bwvauFkU, AK Secret: 6fBbjmvd2T
        ChJTi9gPixZE, STS Token: CAISxAJ1q6Ft5B2yf5jIrSTAG/74uLB13aeARFwQlYXe/lNmoPAtzz2IHhMeXZoA+4YsPu2mmFW6/sdlqdJQpp/QkjJRNF20plM7VtdxAt7I
pbng4YfgbiJREKxaXeirukwDsz9SNTCA     iJlhHL91N0vCGlgpPtpNIRZ4o8I3LGbYMe3XUiTmM3NFkFlyGEe4CFdkf3jm5bHu0WB0gCkk7FO/trLT8L6P5U2DvBWsMyo2eF6TK3F3RNL5gJCnKUM1/QcpGif51/DXQEIvUIYbreL6L9mNxRkY6UgHkpJ
vCxxBmi0fUW5fe3VvPUtVVk900y3LAtQ    U1U1tKDlwTxgBGOFKIQQrKj9PMSqhAcLJtS6MDE7NJKbt10KxV8Qdpz0agaAE7zrIhzsIKFMhIAyquB0Z8/YXeYdmswQUMbqmr+0gX306/0U9iWS612r6AalQSomcAD0eijKFnE8PFyx3YifekZIBCjr17TR
ujPRXpMzvxuXfvzz9eszDB0o0AXX5gTQ    IKDI4Y7necJANrPiAA
Invoke result: 200
All tasks completed.

Analysis based on the log output:

  • On the first call, the cache is empty. The system retrieves a credential based on your configuration and then stores it in the cache.

  • The second call uses the same credential as the first, indicating it was retrieved from the cache.

  • On the third call, the cached credential has expired. Its expiration time (RoleSessionExpiration) is 3,600 seconds, but this call is made 4,200 seconds after the first one. Consequently, the SDK's automatic refresh mechanism fetches a new credential and updates the cache.

  • The fourth call uses the same credential as the third, confirming that the cache was updated.

Related documents