All Products
Search
Document Center

Object Storage Service:Authorize access by using OSS SDK for .NET

Last Updated:Jun 13, 2024

This topic describes how to use temporary access credentials provided by Security Token Service (STS) or a signed URL to authorize temporary access to Object Storage Service (OSS) resources.

Important

A validity period must be specified for STS temporary access credentials and a signed URL. When you use temporary access credentials to generate a signed URL that is used to perform operations, such as object upload and download, the minimum validity period takes precedence. For example, you can set the validity period of your temporary access credentials to 1,200 seconds and the validity period of the signed URL generated by using the credentials to 3,600 seconds. In this case, the signed URL cannot be used to upload objects after the STS temporary access credentials expire, even if the signed URL is within its validity period.

Usage notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

Use STS to authorize temporary access

You can use STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user that is managed by you. For more information about STS, see What is STS?.

STS has the following benefits:

  • You need to only generate a temporary access token and send the access token to a third-party application. You do not need to provide your AccessKey pair to the third-party application. You can specify the access permissions and validity period of this token.

  • The token automatically expires after the validity period ends. Therefore, you do not need to manually revoke the access permissions of a token.

To access OSS by using temporary access credentials provided by STS, perform the following operations:

  1. Obtain temporary access credentials.

    The temporary access credentials consist of an AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. The validity period of temporary access credentials is in seconds. The minimum validity period of temporary access credentials is 900 seconds. The maximum validity period of temporary access credentials is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.

    You can use one of the following methods to obtain temporary access credentials:

    • Method 1

      Call the AssumeRole operation to obtain temporary access credentials.

    • Method 2

      Use STS SDKs to obtain temporary access credentials. For more information, see STS SDK overview.

  2. Use temporary access credentials obtained from STS to create a signed request.

    using Aliyun.OSS;
    // 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. 
    var endpoint = "yourEndpoint";
    Before you run the sample code, make sure that the YOUR_ACCESS_KEY_ID and YOUR_ACCESS_KEY_SECRET environment variables are configured by using the temporary AccessKey pair obtained from STS. 
    var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
    var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
    // Specify the security token obtained from STS. 
    var securityToken = "yourSecurityToken";
    // Use the temporary access credentials obtained from STS to create an OSSClient instance. 
    // Create an OSSClient instance. 
    var ossStsClient = new OssClient(endpoint, accessKeyId, accessKeySecret, securityToken);
    // Perform OSS-related operations.

Use a signed URL to authorize temporary access

Usage notes

  • When you use an OSS SDK to generate a signed URL, the OSS SDK uses a specific algorithm based on the key information stored in the local computer to calculate a signature and adds the signature to a URL to ensure the validity and security of the URL. The operations performed to calculate and construct the URL are completed on the client. You do not need to send requests to the server over the network. This way, you do not need to grant specific permissions to the caller when you generate the signed URL. However, to allow third-party users to perform relevant operations on the resources authorized by the signed URL, you must make sure that the principal that calls the API operations to generate the signed URL has the corresponding permissions.

    For example, if a principal wants to upload an object by using a signed URL, you must grant the oss:PutObject permission to the principal. If a principal wants to download or preview an object by using a signed URL, you must grant the oss:GetObject permission to the principal.

  • You can generate a signed URL and provide the URL to a visitor for temporary access. When you generate a signed URL, you can specify the validity period of the URL to limit the period of time during which the visitor can access specific data.

  • To generate a signed URL that is used to access resources over HTTPS, set the protocol in the endpoint to HTTPS.

  • The signed URL generated by using the following sample code may contain a plus sign (+). In this case, replace the plus sign (+) in the URL with %2B. Otherwise, the signed URL may not be used to access the object as expected.

The following sample code provides examples on how to generate signed URLs and use the signed URLs to upload and download objects. For the complete sample code that you can use to authorize temporary access by using a signed URL, visit GitHub.

Generate a signed URL and use the signed URL to upload a local file

  1. Generate a signed URL

    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    // 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. 
    var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
    var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
    // Specify the name of the bucket. Example: examplebucket. 
    var bucketName = "examplebucket";
    // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
    var objectName = "exampledir/exampleobject.txt";
    var objectContent = "More than just cloud.";
    // Create an OSSClient instance. 
    var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
    try
    {
        // Generate the signed URL. 
        var generatePresignedUriRequest = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Put)
        {
            // Specify the validity period of the signed URL. Default value: 3600. Unit: seconds. 
            Expiration = DateTime.Now.AddHours(1),
        };
        var signedUrl = client.GeneratePresignedUri(generatePresignedUriRequest);
    }
    catch (OssException ex)
    {
        Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
            ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
  2. Upload a local file by using the signed URL

    You can refer to OSS SDK for Android mobile devices. For more information, see Upload an object by using the signed URL.

Generate a signed URL and use the signed URL to download an object

  1. Generate a signed URL

    using Aliyun.OSS;
    using Aliyun.OSS.Common;
    // 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. 
    var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
    var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
    var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
    // Specify the name of the bucket. Example: examplebucket. 
    var bucketName = "examplebucket";
    // Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
    var objectName = "exampledir/exampleobject.txt";
    // Specify the full path of the local file to which you want to download the object. Example: D:\\localpath\\examplefile.txt. If a file that has the same name already exists in the path, the downloaded object overwrites the file. Otherwise, the downloaded object is saved in the path. 
    var downloadFilename = "D:\\localpath\\examplefile.txt";
    // Create an OSSClient instance. 
    var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
    try
    {
        var metadata = client.GetObjectMetadata(bucketName, objectName);
        var etag = metadata.ETag;
        // Generate a signed URL. 
        var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
          {
            // Specify the validity period of the signed URL. Default value: 3600. Unit: seconds. 
            Expiration = DateTime.Now.AddHours(1),
        };
        var uri = client.GeneratePresignedUri(req);
    }
    catch (OssException ex)
    {
        Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
            ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
  2. Download an object by using the signed URL

    You can refer to OSS SDK for Android mobile devices. For more information, see Download an object by using the signed URL.