All Products
Search
Document Center

Object Storage Service:Configure access credentials (Android SDK)

Last Updated:Sep 02, 2026

To send requests to OSS from the Android SDK, configure access credentials. You can choose different credential providers based on your authentication and authorization requirements.

Prerequisites

The OSS Android SDK is installed. Install the Android SDK.

Initialize the credential provider

Choose a credential provider

OSS supports multiple credential provider initialization methods. Choose one based on your scenario.

Important

A mobile device is an untrusted environment. Any full access credential — a long-term AccessKey pair or a temporary STS Token — that reaches the client can be extracted through reverse engineering or runtime debugging. To reduce the risk of data leakage, structure the access path between your mobile app and OSS as follows:

  • Keep long-term AccessKey pairs on your application server. Never ship them to the mobile client.

  • Have the mobile app fetch an STS temporary credential or a presigned URL from your application server before it calls OSS.

  • When using STS temporary credentials, apply a RAM policy that scopes permissions to a single user's object path prefix, and set a short validity period.

  • For uploads and downloads of privacy-sensitive data such as ID cards, facial images, payment credentials, or medical records, have your application server generate a presigned URL for the mobile app to use. The mobile app itself never holds a credential. For details on presigned URLs, see Authorize access (Android SDK).

Credential provider initialization method

Scenario

Requires a pre-configured AccessKey pair or STS token

Underlying credential type

Credential validity

Credential rotation or refresh method

Method 1: Use an AccessKey pair

Secure, stable environments that are not vulnerable to external attacks and require long-term access without frequent credential rotation.

Yes

AccessKey

Long-term

Manual rotation

Method 2: Use an STS token

Untrusted environments where you need to control credential validity and permissions.

Yes

STS token

Temporary

Custom

Method 3: Use CredentialsURI

Applications that obtain credentials from an external system.

No

STS token

Temporary

Auto-refresh

Method 1: Use an AccessKey pair

Use the AccessKey pair (AccessKey ID and AccessKey secret) of an Alibaba Cloud account or a RAM user to initialize the credential provider. This method suits secure, stable environments that require long-term OSS access without frequent credential rotation. Manual key maintenance poses security risks and increases maintenance complexity. To obtain an AccessKey pair, call CreateAccessKey - Create an AccessKey pair for an Alibaba Cloud account or a RAM user.

Warning

This method is not recommended for mobile clients. An Alibaba Cloud account has full permissions on all resources. If the AccessKey pair of an Alibaba Cloud account leaks, your system faces high security risks. If you must use this method, use the AccessKey pair of a RAM user with minimum required permissions.

Sample code

String ak = "<ALIBABA_CLOUD_ACCESS_KEY_ID>";
String sk = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>";

CredentialProvider credentialProvider = new DefaultCredentialProvider(ak, sk);

Method 2: Use an STS token

Use temporary credentials from STS to initialize the credential provider. This suits applications that require temporary OSS access with fine-grained, real-time permission control. The credentials include an AccessKey ID, an AccessKey secret, and an STS token. Manual token maintenance poses security risks and increases maintenance complexity. To obtain an STS token, call AssumeRole - Obtain temporary identity credentials for a RAM role.

The following examples show how to update the STS token manually or automatically.

Manually update the STS token

String ak = "<ALIBABA_CLOUD_ACCESS_KEY_ID>";
String sk = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>";
String token = "<ALIBABA_CLOUD_SECURITY_TOKEN>";

CredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(ak, sk, token);

Automatically update the STS token

CredentialProvider credentialProvider = new OSSFederationCredentialProvider() {
    @Override
    public OSSFederationToken getFederationToken() {

        /* Obtain the AccessKey ID, AccessKey secret, STS token, and expiration time.
         * The following example shows how to obtain the credentials from an application server:
         * URL stsUrl = new URL("<server_url>");
         * 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");
         */
        String ak = "<ALIBABA_CLOUD_ACCESS_KEY_ID>";
        String sk = "<ALIBABA_CLOUD_ACCESS_KEY_SECRET>";
        String token = "<ALIBABA_CLOUD_SECURITY_TOKEN>";
        String expiration = "<ALIBABA_CLOUD_EXPIRATION>";

        // Construct an OSSFederationToken object from the AccessKey ID, AccessKey secret, STS token, and expiration time.
        OSSFederationToken federationToken = new OSSFederationToken(ak, sk, token, expiration);
        return federationToken;
    }
};

Method 3: Use CredentialsURI

Use CredentialsURI to initialize the credential provider when your application needs to obtain credentials from an external system for flexible credential management and keyless access. The underlying implementation uses an STS token. The Credentials tool uses the URI you provide to retrieve an STS token and initialize the client. This eliminates the need to supply an AccessKey pair or STS token directly.

The remote_url (authServerUrl in the sample code) must be provided by a backend service that you deploy yourself. It is not a URL provided by Alibaba Cloud. The Credentials tool sends an HTTP GET request to this URL, and your backend service must return temporary credentials that conform to the protocol described below.

  1. The URI must return a response that conforms to the following protocol:

    • Response status code: 200

    • Response body structure:

      {
        "StatusCode":200,
        "AccessKeyId":"AccessKeyId",
        "AccessKeySecret":"AccessKeySecret",
        "Expiration":"2015-11-03T09:52:59Z",
        "SecurityToken":"SecurityToken"
      }                    

      In the response body, StatusCode is set to 200 by your backend service. The AccessKeyId, AccessKeySecret, Expiration, and SecurityToken fields come from the Credentials object returned by the AssumeRole operation of STS. Your backend service must call AssumeRole to obtain these values and then include them in the response body. For more information about AssumeRole, see Use STS temporary access credentials to access OSS.

    Sample backend service (Python):

    from alibabacloud_sts20150401.client import Client as StsClient
    from alibabacloud_sts20150401 import models as sts_models
    import json
    
    def get_credentials():
        request = sts_models.AssumeRoleRequest(
            role_arn='<your_role_arn>',
            role_session_name='<your_session_name>'
        )
        response = sts_client.assume_role(request)
        creds = response.body.credentials
        return json.dumps({
            'StatusCode': 200,
            'AccessKeyId': creds.access_key_id,
            'AccessKeySecret': creds.access_key_secret,
            'Expiration': creds.expiration,
            'SecurityToken': creds.security_token
        })

    Sample backend service (Node.js):

    const STS = require("@alicloud/sts20150401");
    const stsClient = new STS.default({
      accessKeyId: "<yourAccessKeyId>",
      accessKeySecret: "<yourAccessKeySecret>",
      endpoint: "sts.aliyuncs.com",
    });
    const result = await stsClient.assumeRole("<roleArn>", "<sessionName>");
    const creds = result.body.credentials;
    res.status(200).json({
      StatusCode: 200,
      AccessKeyId: creds.accessKeyId,
      AccessKeySecret: creds.accessKeySecret,
      Expiration: creds.expiration,
      SecurityToken: creds.securityToken,
    });
  2. Configure the URI credential as the access credential.

    String authServerUrl = "<remote_url>";
    OSSAuthCredentialsProvider credentialProvider = new OSSAuthCredentialsProvider(authServerUrl);
    /* If the data is encrypted, you can use the following code to decrypt it.
     * credentialProvider.setDecoder(new OSSAuthCredentialsProvider.AuthDecoder() {
     *     @Override
     *     public String decode(String data) {
     *         String result = null;
     *         // Decrypt the data.
     *         // result = ...
     *         return result;
     *     }
     * });
     */