To make requests to Object Storage Service (OSS) using the C# software development kit (SDK), you must configure access credentials. Alibaba Cloud services use these credentials to verify your identity and access permissions. You can provide credentials in various ways depending on the authentication and authorization requirements of your scenario.
Notes
For information about the regions and endpoints that OSS supports, see Regions and endpoints.
To create an AccessKey pair for a Resource Access Management (RAM) user, see Create an AccessKey pair.
Choose a credential provider
OSS supports multiple ways to initialize a credential provider. You can choose an initialization method based on your authentication and authorization requirements.
Credential provider initialization method | Scenarios | Requires a pre-existing AccessKey pair or Security Token Service (STS) token | Underlying credential type | Credential validity | Credential rotation or refresh method |
Applications that run in a secure and stable environment that is not vulnerable to external attacks. These applications require long-term access to Alibaba Cloud services without frequent credential rotation. | Yes | AccessKey pair | Long-term | Manual rotation | |
Applications that run in an untrusted environment. This method lets you control the validity period and permissions of the access. | Yes | STS token | Temporary | Manual refresh | |
Applications that require authorized access to Alibaba Cloud services, such as cross-account access. | Yes | STS token | Temporary | Auto-refresh | |
Applications that run on Alibaba Cloud ECS instances, ECI instances, or worker nodes of Container Service for Kubernetes. | No | STS token | Temporary | Auto-refresh | |
Untrusted applications that run on worker nodes of Container Service for Kubernetes. | No | STS token | Temporary | Auto-refresh | |
Applications that need to obtain access credentials from an external system. | No | STS token | Temporary | Auto-refresh | |
If none of the preceding methods meet your requirements, you can customize the way you obtain credentials. | Custom | Custom | Custom | Custom |
Common configuration examples
Using a RAM user's AK
If your application is deployed in a secure and stable environment, requires long-term access to OSS, and does not allow for frequent credential rotation, you can initialize the credential provider with the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user. However, this method requires you to manually maintain an AccessKey pair, which increases security risks and maintenance complexity. To obtain an AccessKey pair, see CreateAccessKey - Create an AccessKey pair for an Alibaba Cloud account or a RAM user.
Environment variables
An Alibaba Cloud account has full permissions on all resources. If an AccessKey pair is leaked, it poses significant security risks to your system. We do not recommend using the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user with the minimum required permissions.
Set environment variables using an AccessKey pair.
Mac OS X, Linux, or Unix
export ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>Windows
set ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET>Pass the credential information using environment variables.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Common.Authentication; // Obtain access credentials from environment variables. Before you run this code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are set. var accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, "")); // Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; var conf = new ClientConfiguration(); var client = new OssClient(endpoint, credentialsProvider, conf); client.SetRegion(region);
Static credentials
The following sample code shows how to hard-code access credentials and explicitly set the AccessKey pair to use.
Do not embed access credentials in applications in a production environment. This method is for testing only.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
// Replace the sample values with your actual AccessKey ID and AccessKey secret.
var accessKeyId = "LTAI5tQQx1DWEYK7********" ;
var accessKeySecret = "s5LkMqKmmKbt3zjs7MNJTj********" ;
var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, ""));
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region); Use an STS temporary access credential
If your application requires temporary access to OSS, you can initialize the credential provider with a temporary identity credential (AccessKey ID, AccessKey secret, and security token) obtained from Security Token Service (STS). However, this method requires you to manually maintain an STS token, which increases security risks and maintenance complexity. In addition, to temporarily access OSS multiple times, you must manually refresh the STS token.
To quickly obtain an STS temporary access credential by calling an OpenAPI operation, see AssumeRole - Obtain a temporary identity credential to assume a role.
To obtain an STS temporary access credential using an SDK, see Use an STS temporary access credential to access OSS.
You must specify an expiration time when you generate an STS token. The token automatically becomes invalid after it expires and cannot be used again.
For a list of STS endpoints, see Endpoints.
Environment variables
Set environment variables using a temporary identity credential.
Mac OS X, Linux, or Unix
export ALIBABA_CLOUD_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> export ALIBABA_CLOUD_SECURITY_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>Windows
set OSS_ACCESS_KEY_ID=<ALIBABA_CLOUD_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<ALIBABA_CLOUD_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<ALIBABA_CLOUD_SECURITY_TOKEN>Pass the credential information using environment variables.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Common.Authentication; // Obtain access credentials from environment variables. Before you run this code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN environment variables are set. var accessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); var token = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN"); var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, token)); // Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; var conf = new ClientConfiguration(); var client = new OssClient(endpoint, credentialsProvider, conf); client.SetRegion(region);
Static credentials
You can hard-code credentials in your application to explicitly set the temporary AccessKey pair to use.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
// Replace the sample values with your actual temporary AccessKey ID, AccessKey secret, and security token.
var accessKeyId = "STS.NTZdStF79CVRTQuWCfXTT****";
var accessKeySecret = "5rm8PfEiK8enp56zzAMX4RbZUraoKbWXvCf1xAuT****"
var token = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_SECURITY_TOKEN");
var credentialsProvider = new DefaultCredentialsProvider(new DefaultCredentials(accessKeyId, accessKeySecret, token));
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
More scenario-specific configuration examples
Use RAMRoleARN
If your application requires authorized access to OSS, such as cross-account access, you can initialize the credential provider using a RAMRoleARN. This method uses an STS token as the underlying credential. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the credentials tool retrieves an STS token from the STS service and automatically refreshes the token before it expires. You can also assign a value to policy to restrict the RAM role to a smaller set of permissions.
An Alibaba Cloud account has full permissions on all resources. If an AccessKey pair is leaked, it poses significant security risks to your system. We do not recommend using the AccessKey pair of an Alibaba Cloud account. Instead, use the AccessKey pair of a RAM user with the minimum required permissions.
For more information about how to create an AccessKey pair for a RAM user, see Create an AccessKey pair. The AccessKey ID and AccessKey secret of a RAM user are displayed only when they are created. You must save them promptly. If you forget the AccessKey secret, you must create a new AccessKey pair for rotation.
To obtain a RAMRoleARN, see CreateRole - Create a role.
Install the Alibaba Cloud credentials library. For more information, see Manage access credentials.
Configure access credentials.
using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Common.Authentication; class CredentialsProviderWrapper : ICredentialsProvider { private Aliyun.Credentials.Client client; public CredentialsProviderWrapper(Aliyun.Credentials.Client client) { this.client = client; } public ICredentials GetCredentials() { var accessKeyId = client.GetAccessKeyId(); var accessKeySecret = client.GetAccessKeySecret(); var token = client.GetSecurityToken(); return new DefaultCredentials(accessKeyId, accessKeySecret, token); } public void SetCredentials(ICredentials creds) { } }; 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"), // By default, the following operations use parameter values that are directly entered. You can also add environment variables and use Environment.GetEnvironmentVariable("<variable_name>") to get the corresponding parameters. // The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole RoleArn = "<RoleArn>", // The default environment variable for RoleArn is ALIBABA_CLOUD_ROLE_ARN. // The role session name. RoleSessionName = "<RoleSessionName>", // The default environment variable for RoleSessionName is ALIBABA_CLOUD_ROLE_SESSION_NAME. }; var credentialsClient = new Aliyun.Credentials.Client(config); var credentialsProvider = new CredentialsProviderWrapper(credentialsClient); // Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. const string region = "cn-hangzhou"; var conf = new ClientConfiguration(); var client = new OssClient(endpoint, credentialsProvider, conf); client.SetRegion(region);
Using an ECS RAM role
If your application runs on an Elastic Compute Service (ECS) instance, an Elastic Container Instance (ECI) instance, or a worker node of Container Service for Kubernetes, we recommend that you use an ECSRAMRole to initialize the credential provider. This method uses an STS token as the underlying credential. An ECSRAMRole lets you associate a role with an ECS instance, an ECI instance, or a worker node of Container Service for Kubernetes. This enables the STS token to be automatically refreshed within the instance. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks of manually maintaining them. To obtain an ECSRAMRole, see CreateRole - Create a role.
Install the Alibaba Cloud credentials library. For more information, see Manage access credentials.
Configure an ECSRAMRole as the access credential.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CredentialsProviderWrapper : ICredentialsProvider
{
private Aliyun.Credentials.Client client;
public CredentialsProviderWrapper(Aliyun.Credentials.Client client)
{
this.client = client;
}
public ICredentials GetCredentials()
{
var accessKeyId = client.GetAccessKeyId();
var accessKeySecret = client.GetAccessKeySecret();
var token = client.GetSecurityToken();
return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{
}
};
var config = new Aliyun.Credentials.Models.Config()
{
Type = "ecs_ram_role",
// Optional. The name of the ECS RAM role. If you do not specify this parameter, the role name is automatically obtained. We recommend that you specify this parameter to reduce the number of requests.
RoleName = "<RoleName>"
};
var credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);
Using OIDCRoleARN
After you configure a RAM role for worker nodes in Container Service for Kubernetes, applications in pods on those nodes can retrieve the STS token of the associated role through the global meta service, similar to applications deployed on ECS. However, if you deploy untrusted applications on the container cluster, such as applications submitted by your customers whose code is not visible to you, you may not want them to retrieve the STS token of the instance RAM role associated with the worker nodes through the global meta service. To prevent security risks to your cloud resources while allowing these untrusted applications to securely retrieve the required STS tokens and achieve application-level permission minimization, use the RAM Roles for Service Accounts (RRSA) feature. This method uses an STS token as the underlying credential. An Alibaba Cloud container cluster creates and mounts the corresponding service account OpenID Connect (OIDC) token file for different application pods and injects the relevant configuration information into environment variables. The credentials tool retrieves the configuration information from the environment variables and calls the AssumeRoleWithOIDC operation of STS to exchange the OIDC token for an STS token of the bound role. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks of manually maintaining them. For more information, see Isolate pod permissions based on RRSA.
The following environment variables are injected:
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 path to the OIDC token file.
Configure an OIDCRoleArn as the access credential.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CredentialsProviderWrapper : ICredentialsProvider
{
private Aliyun.Credentials.Client client;
public CredentialsProviderWrapper(Aliyun.Credentials.Client client)
{
this.client = client;
}
public ICredentials GetCredentials()
{
var accessKeyId = client.GetAccessKeyId();
var accessKeySecret = client.GetAccessKeySecret();
var token = client.GetSecurityToken();
return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{}
};
var config = new Aliyun.Credentials.Models.Config()
{
Type = "oidc_role_arn",
// The ARN of the RAM role. You can set RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable.
RoleArn = "<RoleArn>",
// The ARN of the OIDC provider. You can set OidcProviderArn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
OIDCProviderArn = "<OidcProviderArn>",
// The path to the OIDC token file. You can set OidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
OIDCTokenFilePath = "<OidcTokenFilePath>",
// The role session name. You can set RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable.
RoleSessionName = "<RoleSessionName>",
// Optional. A more restrictive access policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"}
Policy = "<Policy>",
RoleSessionExpiration = 3600
};
var credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);Using CredentialsURI
If your application needs to retrieve Alibaba Cloud credentials from an external system to achieve flexible credential management and keyless access, you can initialize the credential provider using a CredentialsURI. This method uses an STS token as the underlying credential. The credentials tool retrieves an STS token from the URI that you provide to complete the credential client initialization. This method does not require you to provide an AccessKey pair or an STS token, which eliminates the risks of manually maintaining them. The backend service that provides the CredentialsURI response must implement an auto-refresh logic for the STS token to ensure that your application can always retrieve valid credentials.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CredentialsProviderWrapper : ICredentialsProvider
{
private Aliyun.Credentials.Client client;
public CredentialsProviderWrapper(Aliyun.Credentials.Client client)
{
this.client = client;
}
public ICredentials GetCredentials()
{
var accessKeyId = client.GetAccessKeyId();
var accessKeySecret = client.GetAccessKeySecret();
var token = client.GetSecurityToken();
return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{}
};
var config = new Aliyun.Credentials.Models.Config()
{
// The credential type.
Type = "credentials_uri",
// The URI from which to obtain credentials. The format is http://local_or_remote_uri/. You can set CredentialsURI using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable.
CredentialsURI = "<CredentialsURI>"
};
var credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);Use a custom access credential
If none of the preceding configuration methods meet your requirements, you can also implement the Credential Providers interface to customize how credentials are provided.
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;
class CustomCredentialsProvider : ICredentialsProvider
{
public CustomCredentialsProvider()
{
}
public ICredentials GetCredentials()
{
// TODO
// Custom method to obtain access credentials.
string accessKeyId;
string accessKeySecret;
//string token;
// Return long-term credentials: access_key_id, access_key_secret.
return new DefaultCredentials(accessKeyId, accessKeySecret, "");
// Return temporary credentials: access_key_id, access_key_secret, token.
// For temporary credentials, you must refresh the credentials based on their expiration time.
// return new DefaultCredentials(accessKeyId, accessKeySecret, token);
}
public void SetCredentials(ICredentials creds)
{
}
};
var credentialsProvider = new CustomCredentialsProvider();
// Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
const string endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";
var conf = new ClientConfiguration();
var client = new OssClient(endpoint, credentialsProvider, conf);
client.SetRegion(region);