All Products
Search
Document Center

Object Storage Service:How to configure access credentials for OSS SDK for .NET

Last Updated:Nov 18, 2024

To use Object Storage Service (OSS) SDK for .NET to initiate a request, you must configure access credentials. Alibaba Cloud services use access credentials to verify identity information and access permissions. You can select different types of access credentials based on your authentication and authorization requirements.

Prerequisites

OSS SDK for .NET is installed. For more information, see Installation.

Select an initialization method

Select a credential provider

OSS supports multiple methods to initialize a credential provider. You can select a suitable method based on the authentication and authorization requirements of your actual scenario.

Initialization method

Scenario

AccessKey pair or security token required

Underlying logic

Credential validity period

Credential rotation or refresh method

Method 1: Use an AccessKey pair

Applications are deployed and run in a secure and stable environment that is not vulnerable to external attacks and need to access cloud services for a long period of time without frequent credential rotation.

Yes

AccessKey pair

Long-term

Manual rotation

Method 2: Use a security token

Applications are deployed and run in an untrusted environment, in which case you want to manage the credential validity period and the resources that can be accessed.

Yes

Security token

Temporary

Manual refresh

Method 3: Use RAMRoleARN

Applications need to be authorized to access cloud services, such as cross-account access.

Yes

Security token

Temporary

Automatic refresh

Method 4: Use ECSRAMRole

Applications are deployed and run on Elastic Compute Service (ECS) instances, elastic container instances, and Container Service for Kubernetes (ACK) worker nodes.

No

Security token

Temporary

Automatic refresh

Method 5: Use OIDCRoleARN

Untrusted applications are deployed and run on ACK worker nodes.

No

Security token

Temporary

Automatic refresh

Method 6: Use CredentialsURI

Applications require access credentials from external systems.

No

Security token

Temporary

Automatic refresh

Method 7: Use custom access credentials

If none of the preceding methods meet your requirements, you can specify a custom method to obtain access credentials.

Custom

Custom

Custom

Custom

Method 1: Use an AccessKey pair

If your application is deployed in a secure and stable environment that is not vulnerable to external attacks and requires long-term access to OSS, you can use an AccessKey pair of your Alibaba Cloud account or a RAM user to initialize a credential provider. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. Take note that this method requires you to manually maintain an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey.

Environment variables

Warning

An Alibaba Cloud account has full access to all resources of the account. Leaks of the Alibaba Cloud account AccessKey pair pose critical threats to the system. Therefore, we recommend that you use the AccessKey pair of a RAM user that is granted the minimum required permissions to initialize a credential provider.

  1. Use the AccessKey pair to specify environment variables.

    Mac OS X/Linux/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>
  2. Use environment variables to pass credentials.

    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    using Aliyun.OSS.Common.Authentication;
    
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured. 
    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 in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);

Method 2: Use a security token

If your application needs to access OSS temporarily, you can use temporary access credentials, which consist of an AccessKey pair and a security token, obtained from Security Token Service (STS) to initialize a credential provider. Take note that this method requires you to manually maintain a security token. This poses security risks and increases maintenance complexity. If you want to access OSS multiple times, you must manually refresh the security token. For more information about how to obtain a security token, see AssumeRole.

Environment variables

  1. Use temporary access credentials to specify environment variables.

    Mac OS X/Linux/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>
  2. Specify environment variables to pass temporary access credentials.

    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    using Aliyun.OSS.Common.Authentication;
    
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET, and OSS_SESSION_TOKEN environment variables are configured. 
    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 in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);
    

Method 3: Use RAMRoleARN

If your application needs to be authorized to access OSS, for example, when you access the OSS resources of another Alibaba Cloud account, you can use RAMRoleARN to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. By specifying the Alibaba Cloud Resource Name (ARN) of a RAM role, the Credentials tool obtains the security token from STS and automatically refreshes the security token before the session expires. You can assign a value to the policy parameter to limit the RAM role permissions. Take note that this method requires you to manually provide an AccessKey pair. This poses security risks and increases maintenance complexity. For more information about how to obtain an AccessKey pair, see CreateAccessKey. For more information about how to obtain the RAM role ARN, see CreateRole.

  1. Install the Alibaba Cloud credential library. For more information, see Manage access credentials.

  2. 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 values of the parameters are directly entered for the following operations. You can also add environment variables and use Environment.GetEnvironmentVariable("<variable name>") to obtain the corresponding parameters.
        // Specify the ARN of the RAM role that you want your application to assume. Example: acs:ram::123456789012****:role/adminrole.
        RoleArn = "<RoleArn>", // By default, the canonical name of the RoleArn environment variable is ALIBABA_CLOUD_ROLE_ARN.
        // Specify the name of the role session.
        RoleSessionName = "<RoleSessionName>", // By default, the canonical name of the RoleSessionName environment variable is ALIBABA_CLOUD_ROLE_SESSION_NAME.
    };
    var credentialsClient = new Aliyun.Credentials.Client(config);
    
    var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
    
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);
    

Method 4: Use ECSRAMRole

If your application runs on an ECS instance, an elastic container instance, or an ACK worker node, we recommend that you use ECSRAMRole to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. ECSRAMRole allows you to attach a RAM role to an ECS instance, an elastic container instance, or an ACK worker node to automatically refresh the security token on the instance. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information about how to obtain the ECSRAMRole role, see CreateRole.

  1. Install the Alibaba Cloud credential library. For more information, see Manage access credentials.

  2. Configure 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. Specify the name of the RAM role of the ECS instance. If you do not specify this parameter, its value is automatically obtained. To reduce the number of requests, we recommend that you specify this parameter.
    RoleName = "<RoleName>"     
};
var credentialsClient = new Aliyun.Credentials.Client(config);

var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);

Method 5: Use OIDCRoleARN

After the RAM role is configured on the ACK worker node, the application in a pod on the node can obtain the security token of the attached role by using the metadata server in the same manner as an application deployed on an ECS instance does. 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 a security token of the RAM role attached to the worker node. To ensure the security of cloud resources, allow untrusted applications to securely obtain the required security token, and minimize application-level permissions, you can use the RAM Roles for Service Account (RRSA) feature. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. ACK creates and mounts corresponding OpenID Connect (OIDC) token files for different application pods, and passes relevant configuration information to environment variables. The Credentials tool obtains the configuration information of environment variables and calls the AssumeRoleWithOIDC operation of STS to obtain the security token of attached roles. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. For more information, 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 Idp.

ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the OIDC token file.

Set OIDCRoleARN to 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",
    // Specify the ARN of the RAM role by specifying the ALIBABA_CLOUD_ROLE_ARN environment variable.
    RoleArn = "<RoleArn>",
    // Specify the ARN of the OIDC IdP by specifying the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable.
    OIDCProviderArn = "<OidcProviderArn>",
    // Specify the path of the OIDC token file by specifying the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable.
    OIDCTokenFilePath = "<OidcTokenFilePath>",
    // Specify the role session name by specifying 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 credentialsClient = new Aliyun.Credentials.Client(config);
var credentialsProvider = new CredentialsProviderWrapper(credentialsClient);
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);

Method 6: Use CredentialsURI

If your application needs to obtain an Alibaba Cloud credential from an external system to implement flexible credential management and keyless access, you can use the CredentialsURI to initialize a credential provider. The underlying logic of this method is to use a security token obtained from STS to configure access credentials. The Credentials tool obtains the security token by using the URI that you specify to initialize an OSSClient instance on the client. This method eliminates the risks that may arise when you manually maintain an AccessKey pair or a security token. Take note that the backend service that provides the CredentialsURI response must automatically refresh the security token to ensure that your application can always obtain a valid 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()
{
    // Specify the credential type. 
    Type = "credentials_uri",
    // Specify the URI of the credential in the http://local_or_remote_uri/ format by specifying 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 in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);

Method 7: Use custom access credentials

If none of the preceding methods meet your requirements, you can specify a custom method to obtain access credentials by calling the CredentialsProvider operation.

using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Common.Authentication;

class CustomCredentialsProvider : ICredentialsProvider
{
    public CustomCredentialsProvider()
    {
    }

    public ICredentials GetCredentials()
    {
        //TODO
        // Specify a custom method to obtain access credentials.

        string accessKeyId;
        string accessKeySecret;
        //string token;

        // Return long-term access credentials, which consists of an AccessKey ID and an AccessKey secret.
        return new DefaultCredentials(accessKeyId, accessKeySecret, "");

        // Return temporary access credentials, which consists of an AccessKey ID, an AccessKey secret, and a security token.
        // Refresh the temporary access credentials based on the expiration time. 
        // return new DefaultCredentials(accessKeyId, accessKeySecrect, token);
    }

    public void SetCredentials(ICredentials creds)
    {
    }
};

var credentialsProvider = new CustomCredentialsProvider();

// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located 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 in which the bucket is located. For example, if the bucket is located 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);

What to do next

After you initialize the credential provider, use the credential provider to create an OSSClient instance. For more information, see Initialization.