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

Notice A validity period must be specified for 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.

Use STS for temporary access authorization

You can use Alibaba Cloud 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 a set of temporary access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user managed by you. For more information about STS, see What is STS?

STS provides the following benefits:

  • You need only to generate an access token and send the access token to a third-party application. You do not need to expose 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. Therefore, you do not need to manually revoke the access permissions of a token.
Note For more information about how to configure STS, see Use a temporary credential provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain temporary access credentials from STS. For more information, see STS SDK overview. The temporary access credentials consist of a temporary AccessKey pair and a security token. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 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.

The following code provides an example on how to generate a signed request by using Security Token Service (STS) credentials:

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>";
// Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
var accessKeyId = "yourAccessKeyId";
var accessKeySecret = "yourAccessKeySecret";
// Specify the security token obtained from STS. 
var securityToken = "yourSecurityToken";
// After you obtain temporary access credentials from STS, you can use the security token and temporary AccessKey pair that are contained in the credentials to create an OSSClient instance. 
// Create an OSSClient instance. 
var ossStsClient = new OssClient(endpoint, accessKeyId, accessKeySecret, securityToken);
// Perform corresponding operations. 

Use a signed URL for temporary access authorization

This section provides examples on how to use a signed URL to authorize temporary access.

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

Notice If you use the following code to generate a signed URL that contains the plus sign (+), you may fail to access OSS by using the URL. In this case, you must replace the plus sign (+) in the URL with %2B.

For the complete sample code that is used to authorize temporary access by means of a signed URL, visit GitHub.

  • Use a signed URL to upload an object

    The following code provides an example on how to use a signed URL to upload an object:

    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";
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in Object Storage Service (OSS) is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    var accessKeyId = "yourAccessKeyId";
    var accessKeySecret = "yourAccessKeySecret";
    // Specify the bucket name. Example: examplebucket. 
    var bucketName = "examplebucket";
    // Specify the full path of the object. The full path of the object cannot contain the bucket name. 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 a 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);
        // Use the signed URL to upload the object. 
        var buffer = Encoding.UTF8.GetBytes(objectContent);
        using (var ms = new MemoryStream(buffer))
        {
            client.PutObject(signedUrl, ms);
        }
        Console.WriteLine("Put object by signatrue succeeded. {0} ", signedUrl.ToString());
    }
    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);
    }
  • Use a signed URL to download an object

    The following code provides an example on how to use a signed URL to download an object:

    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";
    // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
    var accessKeyId = "yourAccessKeyId";
    var accessKeySecret = "yourAccessKeySecret";
    // Specify the bucket name. Example: examplebucket. 
    var bucketName = "examplebucket";
    // Specify the full path of the object. The full path of the object cannot contain the bucket name. Example: exampledir/exampleobject.txt. 
    var objectName = "exampledir/exampleobject.txt";
    // Specify the full path to which you want to download the object. After the object is downloaded to the specified path, the downloaded object is saved as a local file. Example: D:\\localpath\\examplefile.txt. If a file that has the same name already exists in the specified path, the downloaded object overwrites the file. Otherwise, a file is created. 
    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);
        // Use the signed URL to download the object. 
        OssObject ossObject = client.GetObject(uri);
        using (var file = File.Open(downloadFilename, FileMode.OpenOrCreate))
        {
            using (Stream stream = ossObject.Content)
            {
                int length = 4 * 1024;
                var buf = new byte[length];
                do
                {
                    length = stream.Read(buf, 0, length);
                    file.Write(buf, 0, length);
                } while (length != 0);
            }
        }
        Console.WriteLine("Get object by signatrue succeeded. {0} ", uri.ToString());
    }
    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);
    }