All Products
Search
Document Center

Alibaba Cloud SDK:Manage access credentials

最終更新日:Nov 18, 2024

When you call API operations to manage cloud resources by using Alibaba Cloud SDKs, you must configure valid credential information. The Alibaba Cloud Credentials tool provides powerful features that allow you to obtain and manage access credentials with ease. 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 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:

  1. An 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.

  2. 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?

  3. 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.

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.

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

    2. On the Browse tab of the NuGet Package Manager panel, enter Aliyun.Credentials in the search box in the upper-left corner.

    3. In the search results, select the package whose value of the Authors parameter is Alibaba Cloud and click Install.

  1. We recommend that you use the latest version of Alibaba Cloud Credentials for .NET. This ensures that all credentials are supported.

  2. For information about all released versions of Alibaba Cloud Credentials for .NET, see ChangeLog.txt.

Initialize a Credentials client

You can use multiple methods to initialize a Credentials client. Use the Type parameter to specify the method that you want to use to initialize a Credentials client.

Important

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.

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, see the Default credential provider chain section of this topic.

using Aliyun.Credentials.Models;

namespace credentials_demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a Credentials client without specifying a method.
            Config config = new Config();
            var credential = new Aliyun.Credentials.Client(config);
        }
    }
}

Call example

The following sample code shows how to call the DescribeRegions operation of Elastic Compute Service (ECS). Before you call this operation, you must install 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)
        {
            // Use the default credential to initialize a Credentials client. 
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(null);

            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Specify the endpoint of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

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.

Warning

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 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

You can use the Credentials tool to read an AccessKey pair and use the AccessKey pair as a credential to call the API operations of Alibaba Cloud services.

The following sample code shows how to call the DescribeRegions operation of ECS. Before you call this operation, you must install 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)
        {
            // Use an AccessKey pair to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify 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 of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 3: 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 example shows 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", 
                // 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"), 
                // 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();
        }
    }

Call example

You can use the Credentials tool to read an STS token and use the STS token as a credential to call the API operations of Alibaba Cloud services.

The following sample code shows how to call the DescribeRegions operation of ECS. Before you call this operation, you must install ECS SDK for .NET and STS 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)
        {
            // Use an STS token to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify the credential type. 
                Type = "sts", 
                // 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"), 
                // Obtain the STS token 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();
            // Specify the endpoint of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 4: 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 that you want your application to assume. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
                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();
        }
    }
}

Call example

The following sample code shows how to call the DescribeRegions operation of ECS. Before you call this operation, you must install 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)
        {
            // Use an AccessKey pair and a RAM role to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify the credential type. 
                Type = "ram_role_arn",
                // Specify the AccessKey ID. 
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                // Specify the AccessKey secret. 
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                // Specify the ARN of the RAM role that you want your application to assume. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable. Example: acs:ram::123456789012****:role/adminrole.
                RoleArn = "<RoleArn>",
                // Specify the role session name. You can obtain the value from 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();
            // Specify the endpoint of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 5: Use the RAM role of an ECS instance

You can assign a RAM role to an ECS instance or elastic container instance. When you use the Credentials tool on the ECS instance or elastic container instance, the tool automatically obtains the RAM role assigned to the instance and obtains an STS token of the RAM role by accessing the metadata server. Then, a Credentials client can be initialized by using the STS token.

You can access instance metadata in normal or security hardening mode. By default, the Credentials tool obtains access credentials in security-hardening mode by using Instance Metadata Service Version 2 (IMDSv2). You can use the DisableIMDSv1 parameter to specify the exception handling logic if an exception occurs when you use the security hardening mode.

  1. If the parameter is set to false, which is the default value, the access credential is obtained in normal mode.

  2. If the parameter is set to true, an exception is reported. In this case, you can obtain the access credential only in security hardening mode.

Your instance configuration determines whether the instance metadata server supports IMDSv2.

Note
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. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, the value is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
                RoleName = "<RoleName>" 
            };
            // A value of true indicates that the security hardening mode is forcibly used. The default value is false, which indicates that the system attempts to obtain access credentials in security hardening mode first. If the attempt fails, the system switches to normal mode to obtain access credentials by using IMDSv1. 
            // 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();
        }
    }
}

Call example

using System;
using Aliyun.Credentials.Models;
using Tea;
using Tea.Utils;

namespace credentials_demo
{
    public class Sample
    {
        static void Main(string[] args)
        {
            // Use the RAM role of an ECS instance to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify the credential type. 
                Type = "ecs_ram_role",
              	// Optional. Specify the name of the RAM role of the ECS instance. You can obtain the value from the ALIBABA_CLOUD_ECS_METADATA environment variable. If you do not specify this parameter, the value is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
                RoleName = "<RoleName>"
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);

            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Specify the endpoint of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 6: Use the RAM role of an OIDC IdP

After you attach a RAM role to a worker node in a Container Service for Kubernetes cluster, applications in the pods on the worker node can use the metadata server to obtain an STS token in the same way as the applications on ECS instances. However, if an untrusted application is deployed on the worker node, such as an application that is submitted by your customer and whose code is unavailable to you, you may not want the application to use the metadata server to obtain 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 minimum necessary permissions to an application. 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 to obtain 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 to be assumed. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // Specify the ARN of the OIDC IdP. You can obtain the value from the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                OIDCProviderArn = "<OidcProviderArn>",
                // Specify the path of the OIDC token file. You can obtain the value from the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                OIDCTokenFilePath = "<OidcTokenFilePath>",
                // Specify the role session name. You can obtain the value from 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);
        }
    }
}

Call example

The following sample code shows how to call the DescribeRegions operation of ECS. Before you call this operation, you must install 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)
        {
            // Use the RAM role of an OIDC IdP to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify the credential type. 
                Type = "oidc_role_arn",
                // Specify the ARN of the RAM role to be assumed. You can obtain the value from the ALIBABA_CLOUD_ROLE_ARN environment variable.
                RoleArn = "<RoleArn>",
                // Specify the ARN of the OIDC IdP. You can obtain the value from the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
                OIDCProviderArn = "<OidcProviderArn>",
                // Specify the path of the OIDC token file. You can obtain the value from the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
                OIDCTokenFilePath = "<OidcTokenFilePath>",
                // Specify the role session name. You can obtain the value from 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
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);

            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Specify the endpoint of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 7: Use a credential URI

The underlying logic of this method is to use an STS token to initialize a Credentials client. The Credentials tool uses the uniform resource identifier (URI) that you provide to obtain an STS token. The STS token is then used to initialize a 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>"     
            };
        }
    }
}

Call example

To call the API operations of Alibaba Cloud services, you can specify a local or remote URI for credentials and use Alibaba Cloud Credentials to obtain and automatically update an access token based on the local or remote URI.

The following sample code shows how to call the DescribeRegions operation of ECS. Before you call this operation, you must install 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)
        {
            // Use a URI to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify the credential type. 
                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>" 
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);

            AlibabaCloud.OpenApiClient.Models.Config ecsConfig = new AlibabaCloud.OpenApiClient.Models.Config();
            // Specify the endpoint of ECS. 
            ecsConfig.Endpoint = "ecs.cn-beijing.aliyuncs.com";
            // Specify the credential. 
            ecsConfig.Credential = credentialClient;
            // Initialize an ECS SDK client. 
            AlibabaCloud.SDK.Ecs20140526.Client escClient = new AlibabaCloud.SDK.Ecs20140526.Client(ecsConfig);
            // Initialize a request to call the DescribeRegions operation. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest describeInstancesRequest = new AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsRequest();
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the DescribeRegions operation and obtain a response. 
            AlibabaCloud.SDK.Ecs20140526.Models.DescribeRegionsResponse response = escClient.DescribeRegionsWithOptions(describeInstancesRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

Method 8: 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",     
              	// Specify the bearer token.
                BearerToken = "<BearerToken>"      
            };
            var bearerCredential = new Aliyun.Credentials.Client(config);

            string bearerToken = bearerCredential.GetBearerToken();
            string credentialType = bearerCredential.GetType();
        }
    }
}

Call example

The following sample code shows how to call the GetInstance operation of Cloud Call Center. Before you call this operation, you must install Cloud Call Center 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)
        {
            // Use a bearer token to initialize a Credentials client. 
            Aliyun.Credentials.Models.Config credentialsConfig = new Aliyun.Credentials.Models.Config()
            {
                // Specify the credential type. 
                Type = "bearer",
                // Specify the bearer token.
                BearerToken = "<BearerToken>"
            };
            Aliyun.Credentials.Client credentialClient = new Aliyun.Credentials.Client(credentialsConfig);

            AlibabaCloud.OpenApiClient.Models.Config cccConfig = new AlibabaCloud.OpenApiClient.Models.Config()
            {
                // Specify the endpoint of ECS. 
                Endpoint = "ccc.cn-shanghai.aliyuncs.com",
                // Specify the credential. 
                Credential = credentialClient
            };

            # Use the Credentials client to initialize the Cloud Call Center SDK client. 
            AlibabaCloud.SDK.CCC20200701.Client cccClient = new AlibabaCloud.SDK.CCC20200701.Client(cccConfig);
            // Initialize a request to call the GetInstance operation. 
            AlibabaCloud.SDK.CCC20200701.Models.GetInstanceRequest getInstanceRequest = new AlibabaCloud.SDK.CCC20200701.Models.GetInstanceRequest
            {
                InstanceId = "ccc-test",
            };
            // Initialize the runtime configurations. 
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            // Call the GetInstance operation and obtain a response. 
            AlibabaCloud.SDK.CCC20200701.Models.GetInstanceResponse response = cccClient.GetInstanceWithOptions(getInstanceRequest, runtime);
            Console.WriteLine(response.Body.ToMap());
        }
    }
}

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. 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 order described in this section.

1. Obtain the credential information from environment variables

If no credentials are found in the previous step, the Credentials tool 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.

  • If the ALIBABA_CLOUD_ACCESS_KEY_ID (AccessKey ID), ALIBABA_CLOUD_ACCESS_KEY_SECRET (AccessKey secret), and ALIBABA_CLOUD_SECURITY_TOKEN (STS token) system environment variables are specified, the Credentials tool uses the specified STS token as the default credential.

2. Obtain the credential information by using the RAM role of an OIDC IdP

If no credentials are found in the previous step, the Credentials tool obtains the values of the following environment variables:

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 path of the OIDC token file.

If the preceding three environment variables are specified, 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 are found in the previous step, the Credentials tool obtains the credential information from the config.json configuration file. The path of the configuration file varies based on the operating system:

Linux: ~/.aliyun/config.json

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

If the configuration file exists, the application initializes a Credentials client by using credential information that is specified by current in the configuration file. You can also configure the ALIBABA_CLOUD_PROFILE environment variable to specify the credential information. For example, you can set the ALIBABA_CLOUD_PROFILE environment variable to client1.

The value of mode in the config.json configuration file specifies a method for obtaining credential information:

  • AK: uses the AccessKey pair as the credential information.

  • RamRoleArn: uses the ARN of a RAM role to obtain the credential information.

  • EcsRamRole: uses the RAM role assigned to the ECS instance to obtain the credential information.

  • OIDC: uses the ARN and token of an OIDC to obtain the credential information.

  • ChainableRamRoleArn: Uses the chainable RAM role to obtain other credential information that is specified in the JSON file.

Configuration 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
		}
	]
}

4. 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 in security hardening mode. If an exception occurs in the security hardening mode, the Credentials tool obtains the access credential in normal mode. You can also configure the ALIBABA_CLOUD_IMDSV1_DISABLED environment variable to specify an exception handling logic. Valid values of the environment variable:

  1. false: The Credentials tool continues to obtain the access credential in normal mode.

  2. 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.

5. Obtain the credential information based on a URI

If no credentials are found in the previous step, the Credentials tool obtains the value of the ALIBABA_CLOUD_CREDENTIALS_URI environment variable that specifies the URI of the credential. If the URI of the credential exists, the application uses the URI of the credential to obtain an STS token as the default credential.

Switch between credentials

This section describes how 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 = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),          
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET")   
            };
            var akCredential = new Aliyun.Credentials.Client(config1);

            Config config2 = new Config()
            {
               Type = "sts",                    
                AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),          
                AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
                SecurityToken = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN")
            };
            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. 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();
        }
    }
}

References