All Products
Search
Document Center

Object Storage Service:Authorize access

Last Updated:Oct 12, 2023

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.

Usage notes

  • 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 the temporary access credentials that are provided by STS to 1,200 seconds and the validity period of the signed URL generated by using the credentials to 3,600 seconds. In this case, you cannot use the signed URL to upload objects after the temporary access credentials expire, even if the signed URL is within the validity period.

  • 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 the regions and endpoints in OSS, see Regions and endpoints.

  • In this example, an OSSClient instance is created by using an OSS domain name. For more information about how to create an OSSClient instance by using a custom domain name or STS, see Initialization.

Use STS for temporary access authorization

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 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 the validity period of the access token.

  • The access token automatically expires after the validity period. Therefore, you do not need to revoke the access permissions of an access 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 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 the temporary access credentials to upload an object.

require 'aliyun/sts'
require 'aliyun/oss'

sts = Aliyun::STS::Client.new(  . 
  # 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. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the Alibaba Cloud Resource Name (ARN) of the role and the name of the custom role session. 
token = sts.assume_role('role-arn', 'session-name')

client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
  access_key_id: 'token.access_key_id',
  access_key_secret: 'token.access_key_secret',
  # Specify the security token obtained from STS. 
  sts_token: 'token.security_token')

# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Upload the object. 
bucket.put_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')

Use a signed URL for temporary access authorization

You can generate a signed URL and provide the URL to a third-party user 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 third-party user can access the OSS resources.

Important

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

The following code provides an example on how to generate a signed URL and use the signed URL to download objects.

  1. Generate a signed URL to download an object.

    require 'aliyun/oss'
    
    client = Aliyun::OSS::Client.new(
      # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
      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. 
      access_key_id: ENV['OSS_ACCESS_KEY_ID'],
      access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
    )
    # Specify the name of the bucket. Example: examplebucket. 
    bucket = client.get_bucket('examplebucket')
    
    # Generate a signed URL that is used to download the object and set the validity period of the URL to 3600. Unit: seconds. 
    puts bucket.object_url('my-object', true, 3600)
  2. Download an object by using a signed URL on mobile devices or browsers.
    // Enter the generated signed URL. 
    String url = "";
    OkHttpClient client = new OkHttpClient();
    // Use the signed URL to download the object. 
    Request getRequest = new Request.Builder()
            .url(url)
            .get()
            .build();
    client.newCall(getRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.code() == 203 || response.code() >= 300) {
                Log.d("download", "fail");
                Log.d("download", response.body().string());
                return;
            }
            // The object is downloaded. 
            InputStream inputStream = response.body().byteStream();
    
            byte[] buffer = new byte[2048];
            int len;
    
            while ((len = inputStream.read(buffer)) != -1) {
                // Process the downloaded data. For example, display the image or perform a write operation on the object. 
            }
        }
    });
    // Use the signed URL to download the object. 
    NSURL * url = [NSURL URLWithString:urlString];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"download error: %@", error);
            return;
        } else if (((NSHTTPURLResponse*)response).statusCode == 203 ||
                   ((NSHTTPURLResponse*)response).statusCode >= 300) {
            NSString *body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"download error: %@", body);
            return;
        }
        NSLog(@"download success");
    }];
    [sessionTask resume];
    // You can also use the download attribute in the <a> tag of an HTML page or window.open of a web API to obtain an object URL. 

References

  • For more information about how to use STS for temporary access authorization, see Alibaba Cloud OSS SDK for Ruby.

  • For more information about how to add a signature to a URL and forward the signed URL to a third party for authorized access, see Add signatures to URLs.