All Products
Search
Document Center

Object Storage Service:Authorize access by using OSS SDK for Ruby

Last Updated:Aug 30, 2024

This topic describes how to authorize temporary access to Object Storage Service (OSS) by using Security Token Service (STS) and a signed URL, respectively.

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 uploads and downloads, 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.

  • 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 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 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 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 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 an object. 
bucket.put_object('exampleobject.txt', :file => 'D:\\localpath\\examplefile.txt')

Use a signed URL for temporary access authorization

Usage notes

  • When you use an OSS SDK to generate a signed URL, the OSS SDK uses a specific algorithm and 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 the signature and construct the URL are completed on the client. You do not need to send requests to the server over the network. Therefore, you do not have to be granted specific permissions to generate a signed URL However, to prevent third-party users from being unable to perform the operation authorized by the signed URL, you must have the corresponding permission to perform the operation.

    For example, to generate a signed URL for an object download or preview, you must have the oss:PutObject permission.

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

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

  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 3,600 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