In the era of mobile Internet, mobile apps upload more and more data every day. By handing off their data storage issues to OSS, developers can focus more on their app logic.

This article describes how to set up an OSS-based direct data transfer service for a mobile app in 30 minutes. Direct data transfer is a service that allows a mobile app to directly connect to OSS for data upload and download, while only sending the control traffic to the app server.


Setting up an OSS-based direct data transfer service for a mobile app offers the following advantages:

  • More secure upload/download method (temporary and flexible permission assignment and authentication).
  • Low cost. Fewer app servers. The mobile app is directly connected to the cloud storage and only the control traffic is sent to the app server.
  • High concurrency and support for a massive amount of users (OSS has massive bandwidth for uploading and downloading use).
  • Elasticity (OSS’s storage space can be expanded unlimitedly).
  • Convenience. You can easily connect to the MTS -video multiport adapter, Image Service, CDN download acceleration, and other services.

The architecture diagram is as follows:


  • Android/iOS mobile app, which is the app installed on the end user's mobile phone.
  • OSS, short for Alibaba Cloud Object Storage Service, which stores app-uploaded data. For more information, see OSS description on Alibaba Cloud website.
  • RAM/STS, which generates temporary access credentials.
  • App server, which is the background service developed for the Android/iOS mobile app and used to manage the tokens used for data uploading/downloading by the app and the metadata of the app-uploaded data.


  1. Request for a temporary upload credential from the app server.

    The Android/iOS app cannot store AccessKeyID/AccessKeySecret directly, which may cause the risk of information leakage. Therefore, the app must request a temporary upload credential (a token) from the app server. The token is only valid for a certain period. For example, if a token is set to be valid for 30 minutes (editable by the app server), then the Android/iOS app can use this token to upload/download data to/from the OSS within the next 30 minutes. 30 minutes later, the app must request a new token to upload/download data.

  2. The app server checks the validity of the preceding request and then returns a token to the app.
  3. After the cell phone receives this token, it can upload or download data from the OSS.

This article mainly describes the content in the red circle and blue circle of the following figure.

  • The blue circle shows how the app server generates a token.
  • The red circle shows how the Android/iOS app receives the token.

Prerequisites for setting up direct data transfer service

Preparations for setting up direct data transfer service:

  1. Activate the OSS service and create a bucket.
  2. Activate the STS service.
    1. Log on to the OSS console.
    2. On the OSS Overview page, find the Basic Settings area, and click Security Token, as shown in the following figure.
    3. Enter the Quick Security Token Configuration page.
      Note If RAM has not yet been activated, a prompt box to activate RAM appears. Click Activate and perform real-name verification. After the verification is finished, the following page appears. Click Start Authorization.
    4. The system performs authorization automatically. Be sure to save the parameters in the three red boxesoxes in the following figures. Click Save Access Key Information to close the dialog box and complete STS activation.
    5. If you have already created an AccessKeyId/AccessKessKeySecret, the following prompt window appears:
      • Click View, as shown in the following figure.
      • Click Create Access Key, as shown in the following figure.
      • Record parameters 1, 2, and 3, as shown in the following figure.
      • Once you have saved the three parameters, STS activation is complete.

Set up an app server

Configuration of sample app server
Note The app in this example is written in PHP. You may write your app in your preferred language, e.g. Java, Python, Go, Ruby, Node.js, or C#.

This tutorial provides development sample programs available for download in multiple languages. The download addresses are shown at the end of this article.

The downloaded package in each language contains a configuration file named config.json.

"AccessKeyID" : "",
"AccessKeySecret" : "",
"RoleArn" : "",
"TokenExpireTime" : "900",
"PolicyFile": "policy/all_policy.txt"
  1. AccessKeyID: Set it to parameter 1 marked with a red box in the preceding figure.
  2. AccessKeySecret: Set it to parameter 2 marked with a red box in the preceding figure.
  3. RoleArn: Set it to parameter 3 marked with a red box in the preceding figure.
  4. TokenExpireTime: indicates the expiration time of the token obtained by the Android/iOS app. The minimum value is 900s. The default value can be retained.
  5. PolicyFile: indicates the file that lists the permissions the token grants. The default value can be retained.

This document has provided three token files defining the most common permissions in the policy directory. They are:

  • all_policy.txt: specifying a token that grants permissions to create or delete a bucket, or upload, download, or delete a file for this account .
  • bucket_read_policy.txt: specifying a token that grants permission to read the specified bucket for this account.
  • bucket_read_write_policy.txt: specifying a token that grants permission to read and write the specified bucket for this account.

If you want to create a token to grant read and write permissions for the specified bucket, replace $BUCKET_NAME in the bucket_read_policy.txt and bucket_read_write_policy.txt files with the name of the specified bucket.

Explanation of the formats of returned data:
//Correct result returned
    "AccessKeyId":"STS. 3p***dgagdasdg",
//Wrong result returned
    "ErrorMessage":"Specified access key is not found."
Explanation of correct result returned: (The following five variables comprise a token)
  • StatusCode: The status indicates the result that the app retrieves the token. The app returns 200 for successful retrieval of the token.
  • AccessKeyId: indicates the AccessKeyId the Android/iOS app obtains when initializing the OSS client.
  • AccessKeySecret: indicates the AccessKeySecret the Android/iOS app obtains when initializing the OSS client.
  • SecurityToken: indicates the token the Android/iOS app initializes.
  • Expiration: indicates the time when the token expires. The Android SDK automatically determines the validity of the token and then retrieves a new one as needed.
Explanation of wrong result returned:
  • StatusCode: The status indicates the result that the app retrieves the token. The app returns 500 for unsuccessful retrieval of the token.
  • ErrorCode: indicates the error causes.
  • ErrorMessage: indicates the detailed information about the error.
Method for running sample code:
  • For PHP, download and unzip a pack, modify the config.json file, run php sts.php to generate a token, and deploy the program to the specified address.

  • For Java (based on Java 1.7), after downloading and unzipping a pack,

    Run this commandjava -jar oss-token-server.jar (port). If you run java –jar oss-token-server.jar without specifying a port, the program listens to Port 7080. To change the listening port to 9000, run java –jar app-token-server.jar 9000. Specify the port number as needed.

How to upload files from your app to oss

  1. After setting up the app server, write down the server address, which is Then, replace the app server address in the sample project with this address.
  2. Specify the bucket and region for the upload in the sample apps.
  3. Click Set to load the configuration.
  4. Select an image file, set the object name to upload to OSS, and select Upload. Now you can experience the OSS service on Android. Data from the Android app can be uploaded directly to OSS.
  5. After the upload is complete, check that the data is on OSS.

Explanation of core code

OSS initialization

The following explains how to use the Android/iOS SDK to request a token from your app server.

  • Android versions
    //Initialize an OssService for upload and download.
    public OssService initOSS(String endpoint, String bucket, UIDisplayer displayer) {
        OSSCredentialProvider credentialProvider;
        //Use your own class to retrieve an STSToken.
    //Read the server address from app server controls.
        String stsServer = ((EditText) findViewById(;
        //STSGetter class, encapsulating the way of retrieving data from the app server, must be inherited from the class OSSFederationCredentialProvider. The way that your app retrieves tokens depends on the protocol between the app and the app server.
        if (stsServer .equals("")) {
            credentialProvider = new STSGetter();
        }else {
            credentialProvider = new STSGetter(stsServer);
    //Retrieve the bucket name from the controls.
        bucket = ((EditText) findViewById(;
    //Initialize an OSSClient. 
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // Connection time-out. The default value is 15 seconds.
        conf.setSocketTimeout(15 * 1000); // Socket time-out. The default value is 15 seconds.
        conf.setMaxConcurrentRequest(5); // The maximum number of concurrent requests. The default value is 5.
        conf.setMaxErrorRetry(2); // The maximum number of retry attempts after each failed attempt. The default value is 2.
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
        return new OssService(oss, bucket, displayer);
  • iOS version
    //Initialize an OSSClient instance.
    - (void)ossInit {
        //Construct a credential provider for retrieving STSTokens.
        id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
            //Implement a function to synchronize the STSToken retrieved from the server.
            return [self getFederationToken];
        //Use endpoint and the credential provider to initialize an OSSClient.
        client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];

Retrieve tokens from app server for mobile app

The specific method by which the app gets tokens from the app server must be written into the function public OSSFederationToken getFederationToken() { }.
Note you can define the logic for this function; however, the return message must contain this variable: return new OSSFederationToken(ak, sk, token, expiration).Here, ak, sk, token, and expiration must be taken from the body of the message returned by the server.

In this example, you can specify the protocol linking the app and app server.

  • Android version
    public OSSFederationToken getFederationToken() {
        String stsJson;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(stsServer).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                stsJson = response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
        catch (IOException e) {
            Log.e("GetSTSTokenFail", e.toString());
            return null;
        try {
            JSONObject jsonObjs = new JSONObject(stsJson);
            String ak = jsonObjs.getString("AccessKeyId");
            String sk = jsonObjs.getString("AccessKeySecret");
            String token = jsonObjs.getString("SecurityToken");
            String expiration = jsonObjs.getString("Expiration");
            return new OSSFederationToken(ak, sk, token, expiration);
        catch (JSONException e) {
            Log.e("GetSTSTokenFail", e.toString());
            return null;
  • iOS version
    NSURL * url = [NSURL URLWithString:STSServer];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
    NSURLSession * session = [NSURLSession sharedSession];
    NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if (error) {
                                                        [tcs setError:error];
                                                    [tcs setResult:data];
    [sessionTask resume];
    // Implementation of this callback must be synchronized with the returned token, so the task waitUntilFinished is necessary.
    [tcs.task waitUntilFinished];
    if (tcs.task.error) {
        // If the network request fails, the return of nil indicates the token cannot be retrieved. In this case, this OSS request fails.
        return nil;
    } else {
        // Parse the JSON string returned to the network request to get each token field and return an STSToken.
        NSDictionary * object = [NSJSONSerialization JSONObjectWithData:tcs.task.result
        OSSFederationToken * token = [OSSFederationToken new];ni
        token.tAccessKey = [object objectForKey:@"AccessKeyId"];
        token.tSecretKey = [object objectForKey:@"AccessKeySecret"];
        token.tToken = [object objectForKey:@"SecurityToken"];
        token.expirationTimeInGMTFormat = [object objectForKey:@"Expiration"];
        return token;

Download source code

Example program
Download sample code of app server