Set up a direct upload service for mobile applications
This topic describes how to use Security Token Service (STS) to set up a direct data upload service for mobile applications in less than 30 minutes. This service allows your mobile application to upload and download data directly to and from OSS, while your application server manages only the control information, ensuring efficient and secure data transfer.
Why use a direct upload service
In the era of mobile Internet, the amount of data uploaded by mobile apps is increasing. As a developer, you can use OSS to handle various data storage needs and focus on your application logic. The direct upload service for mobile applications based on OSS has the following benefits:
-
Data security: Uses flexible permission management for data uploads and downloads, ensuring greater security.
-
Cost-effective: You do not need to prepare many servers. Mobile applications connect directly to OSS, and only control flows connect to application servers.
-
High concurrency: Easily handles high-concurrency access to ensure a good user experience.
-
Elastic scaling: Storage space scales on demand to meet business growth needs.
-
Data processing: Seamlessly integrates image processing and audio/video transcoding for more flexible data processing.
Prerequisites
-
OSS is activated. For more information, see Activate OSS.
-
A bucket is created. For more information, see Create a bucket.
How direct upload works for mobile applications
The following steps describe the process:
-
The mobile application requests temporary access credentials from the application server.
NoteAndroid and iOS applications cannot directly store AccessKey pairs because this may cause data leaks. Therefore, applications can request an STS token from the application server. STS tokens are time-limited. If the expiration time of an STS token is 30 minutes (specified by the application server), the Android or iOS application can use the token to upload and download data from OSS within the 30-minute period. After the token expires, the application must obtain a new STS token.
-
The application server calls the AssumeRole operation by using STS SDK to obtain temporary access credentials.
-
STS generates and returns temporary access credentials to the application server.
-
The application server returns the temporary access credentials to the client.
-
The mobile application uses OSS SDK to upload files to OSS by using the temporary access credentials.
-
OSS returns a success response to the client.
Procedure
Step 1: Enable STS and configure the application server
1. Create a RAM user in RAM
First, create a RAM user and obtain the corresponding AccessKey pair as the long-term identity credential for the application on the application server.
-
Log on to the RAM console by using your Alibaba Cloud account or as an account administrator.
-
In the left-side navigation pane, choose Identity Management > Users.
-
Click Create User.
-
Enter a Logon Name and Display Name.
-
In the Access Mode section, select Use Permanent AccessKey, and then click OK.
The AccessKey Secret of a RAM user is displayed only when it is created and cannot be viewed later. Keep it safe.
-
Click Copy under Actions to save the AccessKey pair (AccessKey ID and AccessKey Secret).
2. Grant the RAM user the permission to call the AssumeRole operation
After you create a RAM user, you must grant the RAM user the permission to call the AssumeRole operation of STS so that the user can assume a RAM role to obtain temporary credentials.
-
In the left-side navigation pane, choose Identity Management > Users.
-
On the Users page, find the target RAM user and click Grant Permissions on the right side of the RAM user.
-
On the Grant Permission page, select the AliyunSTSAssumeRoleAccess system policy.
NoteThe AliyunSTSAssumeRoleAccess policy is a fixed permission required for calling the AssumeRole operation. This policy is not related to the permissions required to obtain temporary credentials or to initiate OSS requests by using temporary credentials.
Set the resource scope to Account Level, and then click Confirm New Authorization.
-
ClickOK.
3. Create a RAM role in RAM
Create a RAM role for the current Alibaba Cloud account and obtain the ARN of the role (Alibaba Cloud Resource Name) for the RAM user to assume later.
-
In the left-side navigation pane, choose Identity Management > Roles.
-
Click Create Role and set the trusted entity type to Cloud Account.
-
Select the current Alibaba Cloud account and click OK.
-
Enter the role name and click OK.
-
On the RAM role management page, click Copy to save the ARN of the role.
The ARN of the role is in the format of acs:ram::<accountId>:role/oss-web-upload, where accountId is the ID of the current Alibaba Cloud account.
4. Create a permission policy for file upload in RAM
Based on the principle of least privilege, create a custom permission policy for the RAM role to restrict uploads to the specified OSS bucket only.
-
In the left-side navigation pane, choose Permissions > Policies.
-
ClickCreate Policy.
-
On the Create Policy page, click JSON Editor and replace
<Bucket name>in the following script with the bucket nameweb-direct-uploadthat you created in the prerequisites.{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": "oss:PutObject", "Resource": "acs:oss:*:*:<Bucket name>/*" } ] } -
After the policy is configured, click Next to edit policy information.
-
In the Basic Information section, enter the policy name, and then click OK.
5. Grant permissions to the RAM role in RAM
Grant the custom permissions to the RAM role so that the RAM role can obtain the required permissions when it is assumed.
-
In the left-side navigation pane, choose Identity Management > RAM Role.
-
On the RAM Role page, find the target RAM role, and then click Grant Permission on the right side of the RAM role.
-
On the Grant Permission page, select Custom Policy and select the custom policy that you created.
Set Resource Scope to Account Level, and select Custom Policy from the policy type drop-down list to filter.
-
ClickOK.
6. Create an ECS instance as the application server
Create an ECS instance as the application server to generate temporary credentials.
In actual deployment, you can integrate the STS API into your own application server without creating this ECS instance.
|
Parameter |
Example value |
|
Billing method |
Pay-as-you-go |
|
Region |
China (Hangzhou) |
|
Public IP |
Assign a public IPv4 address |
|
Security group |
Open HTTP (TCP: 80) port |
For detailed steps, see Purchase a Linux instance and set up a WordPress website from the console.
7. Obtain temporary credentials on the application server
In a web application, integrate STS SDK into the application server to implement an API for obtaining temporary STS credentials. When this API (/get_sts_token) is accessed by using the HTTP GET method, it generates temporary credentials and returns them to the requester.
The following example shows how to use the Flask framework to quickly build a web application on an ECS instance and implement an API for obtaining temporary STS credentials:
-
Connect to the ECS instance.
For more information, see Purchase a Linux instance and set up a WordPress website from the console.
-
Install Python3.
-
Create a project folder and navigate to the project directory.
mkdir my_web_sample cd my_web_sample -
Install dependencies.
pip3 install Flask pip3 install attr pip3 install yarl pip3 install async_timeout pip3 install idna_ssl pip3 install attrs pip3 install aiosignal pip3 install charset_normalizer pip3 install alibabacloud_tea_openapi pip3 install alibabacloud_sts20150401 pip3 install alibabacloud_credentials -
Write the backend code.
-
Create a
main.pyfile. -
Add the following Python code to the file.
import json from flask import Flask, render_template from alibabacloud_tea_openapi.models import Config from alibabacloud_sts20150401.client import Client as Sts20150401Client from alibabacloud_sts20150401 import models as sts_20150401_models from alibabacloud_credentials.client import Client as CredentialClient app = Flask(__name__) # Replace <YOUR_ROLE_ARN> with the ARN of the RAM role. role_arn_for_oss_upload = '<YOUR_ROLE_ARN>' # Set the region for the STS service, such as cn-hangzhou. region_id = 'cn-hangzhou' @app.route("/") def hello_world(): return render_template('index.html') @app.route('/get_sts_token', methods=['GET']) def get_sts_token(): # When CredentialClient is initialized without parameters, the default credential chain is used. # When running the program locally, use the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to specify the AccessKey pair. # When running on ECS, ECI, or Container Service, use the ALIBABA_CLOUD_ECS_METADATA environment variable to specify the bound instance role. The SDK automatically obtains STS temporary credentials. config = Config(region_id=region_id, credential=CredentialClient()) sts_client = Sts20150401Client(config=config) assume_role_request = sts_20150401_models.AssumeRoleRequest( role_arn=role_arn_for_oss_upload, # Set <YOUR_ROLE_SESSION_NAME> to a custom session name. role_session_name='<YOUR_ROLE_SESSION_NAME>' ) response = sts_client.assume_role(assume_role_request) token = json.dumps(response.body.credentials.to_map()) return token app.run(host="127.0.0.1", port=8000) # To listen on other addresses such as 0.0.0.0, add an authentication mechanism on the server. -
Replace
<YOUR_ROLE_ARN>in the code with the ARN of the role obtained in Step 3. -
Set
<YOUR_ROLE_SESSION_NAME>in the code to a custom session name, such asrole_session_test.
-
-
Start the application by using the AccessKey pair obtained in Step 1.
ALIBABA_CLOUD_ACCESS_KEY_ID=<YOUR_AK_ID> ALIBABA_CLOUD_ACCESS_KEY_SECRET=<YOUR_AK_SECRET> python3 main.py -
Access
http://<public IP address of the ECS instance>/get_sts_tokenin a browser.A successful response example is as follows:
{"AccessKeyId": "STS.NUDRy4pc4PrizHtBYxxx", "AccessKeySecret": "H3gq6ZP2fsapnuDmGcRBxoVfiakxxx", "Expiration": "2024-05-07T09:05:19Z", "SecurityToken": "CAISywJ1q6Ft5B2yfSjIr5bxGcOAnbwV57CCeG7FplkGX9VYnqDliTz2IHhMf3ltAu0ftPUxnxxx"} -
Press
Ctrl + Cto stop the application.
Step 2: Download and install the mobile application
Android
-
Download the mobile application source code.
You can use this mobile application to upload images to OSS. The upload methods support simple upload and resumable upload. In poor network conditions, we recommend that you use resumable upload. You can also use the image processing service to generate thumbnails and add watermarks to images.
-
Open the mobile application and configure the application parameters.
-
STS authentication server: Enter the address of the application server deployed in Step 1: Configure the application server.
-
Upload Bucket: The bucket to which the mobile application uploads data.
-
Region: The region where the upload bucket is located.
-
-
Click Settings.
iOS
-
Download the mobile application source code.
You can use this mobile application to upload images to OSS. The upload methods support simple upload and resumable upload. In poor network conditions, we recommend that you use resumable upload. You can also use the image processing service to generate thumbnails and add watermarks to images.
-
Open the mobile application and configure the application parameters.
Before running the demo, configure the required parameters in the OSSTestMacros.h file: OSS_BUCKET_PRIVATE, OSS_ENDPOINT, and OSS_STSTOKEN_URL. Set OSS_STSTOKEN_URL to the address of the application server deployed in Step 1: Configure the application server.
#ifndef OSSTestMacros_h #define OSSTestMacros_h #define OSS_ACCESSKEY_ID @"AccessKeyID" // RAM user ID #define OSS_SECRETKEY_ID @"AccessKeySecret" // RAM user secret #define OSS_BUCKET_PUBLIC @"public-bucket" // Bucket name #define OSS_BUCKET_PRIVATE @"private-bucket" // Bucket name #define OSS_ENDPOINT @"http://oss-cn-region.aliyuncs.com" // Alibaba Cloud endpoint #define OSS_IMG_ENDPOINT @"http://img-cn-region.aliyuncs.com" // Legacy image service endpoint #define OSS_MULTIPART_UPLOADKEY @"multipart_key" // Object key for multipart upload #define OSS_RESUMABLE_UPLOADKEY @"resumable_key" // Object key for resumable upload #define OSS_CALLBACK_URL @"http://oss-demo.aliyuncs.com:23450" // Callback URL for the application server after a successful object upload #define OSS_CNAME_URL @"http://www.cnametest.com/" // CNAME used to replace the bucket endpoint domain name #define OSS_STSTOKEN_URL @"http://*.*.*.*:*/sts/getsts" // Address of the STS authorization server #define OSS_IMAGE_KEY @"testImage.png" // Name of the test image #define OSS_DOWNLOAD_FILE_NAME @"OSS_DOWNLOAD_FILE_NAME" // Object key used for download #endif /* OSSTestMacros_h */ -
Run the demo.
After the demo runs successfully, the app interface displays a selected image preview at the top, with an imageName input field and a Select button for selecting images, a Put button for uploading images, a Get button for downloading images, a GetResizeImage button for getting thumbnails, a Watermark button for adding watermarks, a triggerCallback for triggering callbacks, an uploadBigFile for uploading large files, and a progress bar with download and cancel buttons at the bottom.
Step 3: Use the direct upload service for mobile applications
-
Set the object name in OSS. Click Upload and select the image to upload.
-
After the upload succeeds, check the upload result in the console.