This topic describes how to authorize temporary access to Object Storage Service (OSS) by using Security Token Service (STS) and a presigned URL, respectively.
Notes
A validity period must be specified for temporary access credentials and a presigned URL. When you use temporary access credentials to generate a presigned 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 presigned URL generated by using the credentials to 3,600 seconds. In this case, the presigned URL cannot be used to upload objects after the STS temporary access credentials expire, even if the presigned 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 resources. STS is a web service with which you can generate temporary access tokens. You can use STS to grant access credentials that have a custom validity period and custom permissions to a third-party application or a RAM user that you manage. For more information, see What is STS?.
Benefits of STS:
You only need to generate an access token and send it to a third-party application. There is no need to expose your AccessKey pair to the third-party application. You can specify the access permissions and the validity period of the token.
You do not need to manually revoke the permissions of an access token, as the token automatically expires after the validity period ends.
To access OSS by using temporary access credentials generated with STS, proceed with the following steps:
Obtain temporary access credentials
A temporary access credential consists of an AccessKey pair and a security token. An 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.
Method 2:
Use STS SDKs.
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 presigned URL for temporary access authorization
Usage notes
When you use an OSS SDK to generate a presigned 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 it. 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 presigned URL. However, to prevent third-party users from being unable to perform the operation authorized by the presigned URL, you must have the corresponding permission.
For example, to generate a presigned URL for an object download or preview, you must have the oss:PutObject permission.
You can generate a presigned URL and provide the URL to a visitor for temporary access. When you generate a presigned 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 presigned URL that is used to access resources over HTTPS, set the protocol in the endpoint to HTTPS.
The presigned 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 presigned URL may not be used to access the object as expected.
Generate a presigned URL and use it to download an object
Generate a presigned 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 presigned URL that is used to download the object and set its validity period to 3,600 seconds. puts bucket.object_url('my-object', true, 3600)
- 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 create a presigned URL, see Include a V1 signature in a URL.