OSS SDK for Android provides two authentication modes to ensure the data security of mobile devices: STS authentication mode and self-signed mode.

Notice When you use either the STS authentication mode or self-signed mode, ensure that the callback function that you implement returns results. If you must obtain the token and signature from the app server by sending a request in the callback function, we recommend that you call the synchronous API operations in the network library. The callback function is run in the child thread of the request generated by the SDK and does not block the main thread.

STS authentication mode

You can use Alibaba Cloud Security Token Service (STS) to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for cloud computing users. You can use STS to grant a third-party application or a RAM user (whose user ID you manage) an access credential with a customized validity period and permissions. For more information about STS, see What is STS?

STS has the following benefits:

  • You only need to generate an access token and send the access token to a third-party application, rather than exposing your long-term key (AccessKey) to the third-party application. You can customize the access permissions and validity period of this token.
  • The access token automatically expires when the validity period ends.

The following figure shows the interaction process of STS authentication for an app.

The interaction process is described as follows:

  1. Log on to the app. You can manage your app ID. You can build your own ID management system or use an external web account or OpenID. AppServer can define the principle of least privilege (POLP) of each valid app user.
  2. AppServer requests a security token from STS. Before you call STS API operations, AppServer determines the POLP (described in policy syntax) of the app user and the validity period of the temporary security token. Then, AppServer calls the AssumeRole API operation of STS to obtain the security token. For more information about the roles and usage, see RAM role overview in the RAM User Guide.
  3. STS returns a valid access credential called FederationToken in the app to AppServer, including a security token, a temporary AccessKey pair (AccessKey ID and AccessKey secret), and the expiration time.
  4. AppServer returns the FederationToken to ClientApp. ClientApp caches this credential. When the credential becomes invalid, ClientApp must request a new valid access credential from the AppServer. For example, if the access credential is valid for one hour, the ClientApp can request the AppServer to update the access credential every 30 minutes.
  5. ClientApp uses the locally cached FederationToken to call API operations provided by OSS. OSS detects the STS credential, verifies the credential based on STS, and correctly responds to user requests.

For more information about STS security tokens, see RAM role overview in the RAM User Guide. You can call the AssumeRole API operation provided by STS to obtain the valid access credential. You can also directly use STS SDKs to call this method.

Note To use the STS authentication mode, you must first activate Alibaba Cloud RAM.
  • Obtain the STSToken manually

    You can obtain an STSToken in the app by a certain method, for example, sending a request to the app server, and use the STSToken to initialize the SDK. If this method is adopted, you must follow the expiration time of the STSToken. When the STSToken is about to expire, you must take the initiative to update the new STSToken for the SDK.

    The following code provides an example on how to use an obtained STSToken to initialize the SDK:

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

    When the STSToken is about to expire, you can create a new OSSClient or update OSSStsTokenCredentialProvider by using the following method:

    oss.updateCredentialProvider(new OSSStsTokenCredentialProvider("<StsToken.AccessKeyId>", "<StsToken.SecretKeyId>", "<StsToken.SecurityToken>"));
    					
  • Obtain the STSToken by implementing callback

    If you want the SDK to automatically update the STSToken, you must implement callback in your app. The app uses the callback to obtain a FederationToken (STSToken) and returns it to the SDK. The SDK uses the STSToken for signing. When the STSToken needs to be updated, the SDK calls the callback to obtain a new token.

    String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    
    OSSCredentialProvider credentialProvider = new OSSFederationCredentialProvider() {
    
        @Override
        public OSSFederationToken getFederationToken() {
        // Implement a method to obtain a FederationToken and return it as an OSSFederationToken object.
            // If the FederationToken is not obtained, nil is returned.
    
            OSSFederationToken * token;
            // The following code is used to obtain the STSToken in certain methods, for example, sending request to the app server.
            ...
            return token;
        }
    };
    
    OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
    					
    Note Additionally, if you have obtained all fields required to generate a token in other methods, you can also return these fields by using the callback. In this case, you must manually update the token, and then reconfigure OSSCredentialProvider of the OSSClient instance.

    If the URL of the server from which you request a token is http://localhost:8080/distribute-token.json, the following data is returned:

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

    The following code provides an example on 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;
        }
    };
    					

Self-signed mode

You can store your AccessKey pair in the app server, and use SDK to implement callback in your app. To sign a string, post the string to the app server and use the algorithm specified by OSS to sign the string on the app server. The signed string is returned to the callback function and is sent to the app server as the callback information.

For more information about the signature algorithm, see Add signatures to headers.

The content is concatenated by parameters in the request as follows:

signature = "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content))
			

The following code provides an example on how to use the self-signed mode:

String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";

credentialProvider = new OSSCustomSignerCredentialProvider() {
    @Override
    public String signContent(String content) {
    // Sign a string by using the signature algorithm specified by OSS, concatenate your AccessKey ID to the signature string, and return the result.
        // Post the string to your app server and return the signature.
        // If the signing fails, return nil with the error message.

        // The following code is a demo using a local signature algorithm.
        return "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content));
    }
};

OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);