This topic describes how to set up a direct data transfer service for a mobile app within 30 minutes by using the STS policy. Direct data transfer allows a mobile app to directly connect to OSS for data uploads and downloads, while only the control flow is sent to the app server.

Prerequisites

You have activated OSS and created one or more buckets.

Background information

In the era of mobile Internet, mobile apps are used to upload increasing amounts of data. Developers can hand off their data storage concerns to OSS and focus more on the development of app logic.

OSS-based direct data transfer for mobile apps has the following benefits:
  • Data security: allows mobile apps to upload and download data based on flexible authorization and authentication methods, which delivers better security.
  • Cost-effectiveness: Fewer app servers are required, which minimizes costs. The mobile app is directly connected to OSS for data uploads and downloads, while only the control flow is sent to the app server.
  • High concurrency: supports concurrent access from a large number of users.
  • Elastic scalability: provides storage space that can be scaled as needed.
  • Data processing: used with Image Processing (IMG) and ApsaraVideo Media Processing to facilitate flexible data processing.

Principles

The development process of the direct data transfer service for mobile apps is as follows.
Roles are analyzed as follows:
  • Android- or iOS-based mobile app: the app on the user's mobile phone that applies for and uses STS credentials from the app server.
  • OSS: processes data requests from mobile apps.
  • RAM/STS: generates temporary upload credentials (or tokens).
  • App server: the backend service developed for the Android- or iOS-based mobile app. The app server is used to manage the tokens used for data uploads and downloads through the app and the metadata of the app-uploaded data.

The procedure is as follows:

  1. The mobile app applies for a temporary upload credential from the app server.
    AccessKey pairs cannot be stored in the Android- or iOS-based app because of data leaks. Therefore, the app must apply for a token from the app server. The token is valid only for a specified period. If the token is set to 30 minutes (specified by the app server), the Android- or iOS-based app can use this token to upload or download data to or from OSS within the 30 minutes. After 30 minutes, the app must request a new token to upload or download data.
  2. The app server checks the validity of the request and then returns a token to the mobile app.
  3. The Android- or iOS-based mobile app uses this token to upload data to or download data from OSS.

The following section describes how to use the app server to generate a token and how to use the Android- or iOS-based mobile app to obtain a token.

Step 1: Activate STS

  1. Log on to the OSS console.
  2. In the left-side navigation pane, click Overview.
  3. In the Basic Settings section, choose Security Token (Authorization for RAM Users) > RAM Console.
  4. Click Start Authorization. Complete authorization as prompted.
  5. After authorization is completed, save the AccessKeyID, AccessKeySecret, and RoleArn parameters.
    • If you have not created an AccessKey pair, the system automatically creates an AccessKey pair. Save AccessKeyID, AccessKeySecret, and RoleArn, as shown in the following figures.
    • If you have created an AccessKey pair, click View to create an AccessKey pair, as shown in the following figure.

Step 2: Configure the app server

  1. Download the app server code.
    Language Download link
    PHP Download
    Java Download
    Ruby Download
    Node.js Download
    Go Download
  2. Modify the configuration file.
    The following code sample is written in PHP. Each downloaded package for a specific programming language contains a config.json configuration file, which contains the following information:
    {
    "AccessKeyID" : "",
    "AccessKeySecret" : "",
    "RoleArn" : "",
    "TokenExpireTime" : "900",
    "PolicyFile": "policy/bucket_write_policy.txt"
    }
    The parameters are described as follows:
    • AccessKeyID: Enter the AccessKey ID obtained in Step 5.
    • AccessKeySecret: Enter the AccessKey secret obtained in Step 5.
    • RoleArn: Enter the RoleArn obtained in Step 5.
    • TokenExpireTime: specifies the validity period of the token obtained through the Android- or iOS-based app. The minimum value is the same as the default value, which is 900s.
    • PolicyFile: specifies the file that lists the permissions the token grants. The default value can be retained.
    This topic describes two token files that define the most common permissions in the policy directory. To use the token file, replace $BUCKET_NAME and $OBJECT_PREFIX with specified values.
    • bucket_read_policy.txt: specifies that the token grants permissions to read data from the specified bucket and objects whose names have the specified prefix for the account.
    • bucket_write_policy.txt: specifies that the token grants permissions to write data to the specified bucket and objects whose names have the specified prefix for the account.

    Follow the principle of least privilege (PoLP) based on business requirements. Specifying all resources (resource:*) or all actions (action:*) may cause security risks such as data leaks because of excess permissions.

    Warning The code sample is for reference only. In practice, the online system must implement permission isolation based on different users or devices. This way, tokens that grant different permissions are generated to avoid excess permissions.
  3. Run the code sample.
    Run the code sample as follows:
    • Run the sample code in PHP: After the package is downloaded and decompressed, modify the config.json file. Run the php sts.php command to generate a token. Deploy the program to the app server address.
    • Run the sample code that depends on Java 1.7 in Java: After the package is downloaded and decompressed, modify the config.json file. Reopen the package and run the java -jar app-token-server.jar (port) command. If the port is not specified, run the java -jar app-token-server.jar command. The program will listen to port 7080.
    Sample responses:
    // Sample success responses
    {
        "StatusCode":200,
        "AccessKeyId":"STS.3p***dgagdasdg",
        "AccessKeySecret":"rpnwO9***tGdrddgsR2YrTtI",
       "SecurityToken":"CAES+wMIARKAAZhjH0EUOIhJMQBMjRywXq7MQ/cjLYg80Aho1ek0Jm63XMhr9Oc5s˙∂˙∂3qaPer8p1YaX1NTDiCFZWFkvlHf1pQhuxfKBc+mRR9KAbHUefqH+rdjZqjTF7p2m1wJXP8S6k+G2MpHrUe6TYBkJ43GhhTVFMuM3BZajY3VjZWOXBIODRIR1FKZjIiEjMzMzE0MjY0NzM5MTE4NjkxMSoLY2xpZGSSDgSDGAGESGTETqOio6c2RrLWRlbW8vKgoUYWNzOm9zczoqOio6c2RrLWRlbW9KEDExNDg5MzAxMDcyNDY4MThSBTI2ODQyWg9Bc3N1bWVkUm9sZVVzZXJgAGoSMzMzMTQyNjQ3MzkxMTg2OTExcglzZGstZGVtbzI=",
       "Expiration":"2017-12-12T07:49:09Z",
    }
    // Sample error responses
    {
        "StatusCode":500,
        "ErrorCode":"InvalidAccessKeyId.NotFound",
        "ErrorMessage":"Specified access key is not found."
    }
    A token in a sample success response consists of the following variables:
    • StatusCode: indicates the status of the operation to obtain the token. If the token is obtained, 200 is returned.
    • AccessKeyId: the AccessKey ID obtained when the Android- or iOS-based mobile app initializes OSSClient.
    • AccessKeySecret: the AccessKey secret obtained when the Android- or iOS-based mobile app initializes OSSClient.
    • SecurityToken: the token obtained when the Android- or iOS-based mobile app initializes OSSClient.
    • Expiration: the time when the token expires. The Android SDK automatically determines whether the token is valid. If the token becomes invalid, another token is automatically obtained.
    The error codes are described as follows:
    • StatusCode: indicates the status of the operation to obtain the token. If the token fails to be obtained, 500 is returned.
    • ErrorCode: indicates the cause of the error.
    • ErrorMessage: indicates the specific description of the error.

Step 3: Download and install the mobile app

  1. Download the app source code.
    Download link:

    You can use either of the mobile apps to upload images to OSS. Simple upload and resumable upload are supported. If the network quality is poor, we recommend that you use resumable upload. You can also use Image Processing (IMG) to resize an image to obtain a thumbnail and add watermarks to the image.

  2. Open the mobile app and configure the app parameters.
    • App server: Enter the app server address specified in Step 2: Configure the app server.
    • Destination bucket: the bucket to which the data is uploaded from a mobile app.
    • Region: the region where the destination bucket is located.
    • OSS object name: The name must contain the prefix specified in the policy configuration file of the app server.
  3. Click Set to load configurations.

Step 4: Experience direct data transfer for mobile apps

  1. Open the mobile app.
  2. Click Select Image. Select the image to be uploaded and configure the object name.
  3. After the object is completed, view the upload result through the console.

Core code analysis

The code for OSS initialization is analyzed as follows:

  • Android version
    // We recommend that you use OSSAuthCredentialsProvider. The token is automatically updated after it expires.
    String stsServer = "app server address such as http://abc.com:8080"
    OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer);
    //config
    ClientConfiguration conf = new ClientConfiguration();
    conf.setConnectionTimeout(15 * 1000); // The connection timeout period. Default value: 15s.
    conf.setSocketTimeout(15 * 1000); // The socket timeout period. Default value: 15s.
    conf.setMaxConcurrentRequest(5); // The maximum number of concurrent requests. Default value: 5.
    conf.setMaxErrorRetry(2); // The maximum number of retry attempts. Default value: 2.
    OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
  • iOS version
    OSSClient * client;
    ...
    // We recommend that you use OSSAuthCredentialProvider. The token is automatically updated after it expires.
    id<OSSCredentialProvider> credential = [[OSSAuthCredentialProvider alloc] initWithAuthServerUrl:@"the app server address such as http://abc.com:8080"];
    client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];