All Products
Search
Document Center

Object Storage Service:Authorize access (Android SDK)

Last Updated:Dec 16, 2025

The Android software development kit (SDK) provides the STS authentication mode, self-signed mode, and presigned URLs to secure mobile devices.

Background information

For both the STS authentication and self-signed modes, the callback function that you implement must return the token and signature when called. To send a network request to your application server to obtain the token and signature, you can call the synchronous API of the network library. The callback runs in a subthread when the SDK initiates a request and therefore does not block the main thread.

STS authentication mode

Note

To use the STS mode for authorization, you must first activate Alibaba Cloud Resource Access Management (RAM).

You can use Alibaba Cloud Security Token Service (STS) for temporary authorized access to OSS. STS is a web service that provides temporary access tokens for cloud computing users. Using STS, you can issue an access credential with a custom time-to-live (TTL) and custom permissions to a third-party application or a federated user whose identity you manage. For more information, see What is STS?.

STS provides the following benefits:

  • You do not need to expose your long-term AccessKey pair to a third-party application. Instead, you can generate an access token with custom access permissions and a specific validity period to provide to the application.

  • You do not need to manage permission revocation because the access token automatically becomes invalid when it expires.

To use STS to grant temporary access to OSS, follow these steps:

  1. Obtain temporary access credentials.

    Temporary access credentials include a temporary AccessKey pair, which consists of an AccessKey ID and an AccessKey secret, and a security token. The validity period of temporary access credentials is measured in seconds. The minimum value is 900. The maximum value is the maximum session duration that is set for the current RAM role. For more information, see Set the maximum session duration for a RAM role.

    You can obtain temporary access credentials in one of the following two ways:

  2. Use the temporary access credentials to initialize the SDK.

    String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    
    OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider("StsToken.AccessKeyId", "StsToken.SecretKeyId", "StsToken.SecurityToken");
    
    OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);                  

    When you initialize the SDK with temporary access credentials, be aware of the validity period of the StsToken.

    The following code shows how to update the StsToken when its remaining validity period is less than 5 minutes:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = sdf.parse("<StsToken.Expiration>");
    long expiration = date.getTime() / 1000;
    // If the StsToken is about to expire in less than 5 minutes, update the StsToken.
    if (DateUtil.getFixedSkewedTimeMillis() / 1000 > expiration - 5 * 60) {
        oss.updateCredentialProvider(new OSSStsTokenCredentialProvider("StsToken.AccessKeyId", "StsToken.SecretKeyId", "StsToken.SecurityToken"));
    }
    • Manually update the StsToken

      When the StsToken is about to expire, you can reconstruct the OSSClient or update the CredentialProvider as follows:

      oss.updateCredentialProvider(new OSSStsTokenCredentialProvider("StsToken.AccessKeyId", "StsToken.SecretKeyId", "StsToken.SecurityToken"));                   
    • Automatically update the StsToken

      To enable the SDK to automatically update the StsToken, you must implement a callback in your application. The SDK calls the callback that you implement to obtain a Federation Token (StsToken). The SDK then uses this token for signing and calls the callback to obtain a new StsToken when the current one is about to expire.

      String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
      
      OSSCredentialProvider credentialProvider = new OSSFederationCredentialProvider() {
      
          @Override
          public OSSFederationToken getFederationToken() {
          // Obtain the FederationToken and construct it as an OSSFederationToken object to return. If the FederationToken fails to be obtained for any reason, the server directly returns null.
      
              OSSFederationToken token;
              // Obtain the token from your server.
              return token;
          }
      };
      
      OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);                    
      Note

      If you have already obtained the required fields for the StsToken through other means, you can also return the StsToken directly in the callback. However, you must manually handle the StsToken update and reset the OSSCredentialProvider for the OSSClient instance after the update.

      For example, if you access the server at http://localhost:8080/distribute-token.json, the following data is returned:

      {
          "StatusCode": 200,
          "AccessKeyId":"STS.iA645eTOXEqP3cg3****",
          "AccessKeySecret":"rV3VQrpFQ4BsyHSAvi5NVLpPIVffDJv4LojU****",
          "Expiration":"2015-11-03T09:52:59Z",
          "SecurityToken":"CAES7QIIARKAAZPlqaN9ILiQZPS+JDkS/GSZN45RLx4YS/p3OgaUC+oJl3XSlbJ7StKpQ****"}                    

      The following example shows how to implement OSSFederationCredentialProvider:

      OSSCredentialProvider credetialProvider = new OSSFederationCredentialProvider() {
          @Override
          public OSSFederationToken getFederationToken() {
              try {
                  URL stsUrl = new URL("http://localhost:8080/distribute-token.json");
                  HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
                  InputStream input = conn.getInputStream();
                  String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
                  JSONObject jsonObjs = new JSONObject(jsonText);
                  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 (Exception e) {
                  e.printStackTrace();
              }
              return null;
          }
      };                    

Presigned URL

Notes

  • When you use an OSS SDK to generate a presigned URL, the OSS SDK uses a specific algorithm based on 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 and construct the URL are completed on the client. You do not need to send requests to the server over the network. This way, you do not need to grant specific permissions to the caller when you generate the presigned URL. However, to allow third-party users to perform relevant operations on the resources authorized by the presigned URL, you must make sure that the principal that calls the API operations to generate the presigned URL has the corresponding permissions.

    For example, if a principal wants to upload an object by using a presigned URL, you must grant the oss:PutObject permission to the principal. If a principal wants to download or preview an object by using a presigned URL, you must grant the oss:GetObject permission to the principal.

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

The following examples show how to use presigned URLs for temporary authorization.

Generate a presigned URL and use it to upload a file

  1. Generate a presigned URL for an upload.

    // Specify the bucket name, for example, examplebucket.
    String bucketName = "examplebucket";
    // Specify the full path of the source object, without the bucket name, for example, exampleobject.txt.
    String objectKey = "exampleobject.txt";
    // Set the content-type.
    String contentType = "application/octet-stream";
    String url = null;
    try {
        // Generate a presigned URL for uploading the file.
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
        // Set the expiration time of the presigned URL to 30 minutes.
        request.setExpiration(30*60);
        request.setContentType(contentType);    
        request.setMethod(HttpMethod.PUT);
        url = oss.presignConstrainedObjectURL(request);
        Log.d("url", url);
    } catch (ClientException e) {
        e.printStackTrace();
    }
  2. Upload a file using the presigned URL.

    // Specify the generated presigned URL.
    String url = "";
    // Specify the full path of the local file.
    String localFile = "/storage/emulated/0/oss/examplefile";
    // Set the content-type.
    String contentType = "application/octet-stream";
    // Upload the file using the presigned URL.
    OkHttpClient client = new OkHttpClient();
    Request putRequest = new Request.Builder()
            .url(url)
            .put(RequestBody.create(MediaType.parse(contentType), new File(localFile)))
            .build();
    client.newCall(putRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("response", response.body().string());
        }
    });

Generate a presigned URL and use it to download a file

  1. Generate a presigned URL for a download.

    // Specify the bucket name, for example, examplebucket.
    String bucketName = "examplebucket";
    // Specify the full path of the source object, without the bucket name, for example, exampleobject.txt.
    String objectKey = "exampleobject.txt";
    String url = null;
    try {
        // Generate a presigned URL for downloading the file.
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
        // Set the expiration time of the presigned URL to 30 minutes.
        request.setExpiration(30*60);
        request.setMethod(HttpMethod.GET);
        url = oss.presignConstrainedObjectURL(request);
        Log.d("url", url);
    } catch (ClientException e) {
        e.printStackTrace();
    }
  2. Download a file using the presigned URL.

    // Specify the generated presigned URL.
    String url = "";
    OkHttpClient client = new OkHttpClient();
    // Download the file using the presigned URL.
    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 request was successful.
            InputStream inputStream = response.body().byteStream();
    
            byte[] buffer = new byte[2048];
            int len;
    
            while ((len = inputStream.read(buffer)) != -1) {
                // Process the downloaded data, such as displaying an image or writing to a file.
            }
        }
    });