Object Storage Service (OSS) SDK for Android provides two authentication modes to ensure the data security of mobile devices: the Security Token Service (STS) authentication mode and the self-signed mode.

Overview

When you use the STS authentication mode or self-signed mode, ensure that the callback function that you implement returns results for Token and Signature. 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 included 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

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

You can use STS to authorize temporary access to OSS. STS is a web service that provides temporary access tokens for users. You can use STS to grant an access credential that has a custom validity period and custom permissions for a third-party application or a Resource Access Management (RAM) user managed by you. For more information about STS, see What is STS?.

STS has the following benefits:

  • You need only to generate an access token and send the access token to a third-party application, instead of exposing your AccessKey pair to the third-party application. You can customize the access permissions and validity period of this token.
  • The access token automatically expires after the validity period. Therefore, you do not need to manually revoke the permissions of an access token.
Note For more information about how to set up STS, see Use a temporary credential provided by STS to access OSS in OSS Developer Guide. You can call the AssumeRole operation or use STS SDKs for various programming languages to obtain a temporary access credential. The temporary access credential contains a security token and a temporary AccessKey pair that consists of an AccessKey ID and an AccessKey secret. The minimum validity period of a temporary access credential is 900 seconds. The maximum validity period of a temporary access credential is the maximum session duration specified for the current role. For more information, see Specify the maximum session duration for a RAM role.
  • Configure an STS token

    You can obtain an STS token in the app by a method, such as sending a request to the app server, and use the STS token to initialize the SDK. If you use this method, you must pay attention to the validity period of the STS token. When the STS token is about to expire, you must update the new STS token for the SDK.

    The following code provides an example on how to use an STS token 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 STS token is about to expire, you can create a new OSSClient or update CredentialProvider by using the following method:

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

    If you want the SDK to automatically update the STS token, you must implement callback in your app. The app uses the callback to obtain a federation token (STS token) and returns the token to the SDK. The SDK uses the STS token to generate signatures. When the STS token 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() {
        // Obtain a federation token, construct the token, and then return the token as an OSSFederationToken object. If you fail to obtain the federation token, null is returned. 
    
            OSSFederationToken token;
            // Obtain a federation token from your server. 
            return token;
        }
    };
    
    OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
                        
    Note Additionally, if you obtain all fields required to generate a token in other ways, 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.iA645eTOXEqP3cg3****",
        "AccessKeySecret":"rV3VQrpFQ4BsyHSAvi5NVLpPIVffDJv4LojU****",
        "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 perform the following operations to save the AccessKey ID and AccessKey secret on your own server and then use them to sign the client information.
  1. Obtain the string-to-sign from the client and send the string to your own server.
    1. Use the signContent method of OSSCustomSignerCredentialProvider provided by OSS SDK for Android to obtain the string-to-sign when you create the request.
    2. Send the string-to-sign to your own server.
  2. Sign the string on your own server and return the signed string to the client.
    1. Use the specified signature algorithm to sign the string. For more information about the signature algorithm, see Add signatures to headers.

      The signature is in the following format: signature = "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content)), in which content is the string that is concatenated based on the request parameters.

    2. Return the signed string to the client.

      For example, the URL of the server is http://localhost:8080/sign. You can send the content to the server to generate a signature, and the server returns the signature to the client. The following code provides an example on how to sign the string based on the signature algorithm.

      String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
      
      OSSCredentialProvider credentialProvider = new OSSCustomSignerCredentialProvider() {
          @Override
          public String signContent(String content) {
              URL stsUrl = new URL("http://localhost:8080/sign?content=" + content);
              HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
              InputStream input = conn.getInputStream();
              String jsonText = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
              JSONObject jsonObjs = new JSONObject(jsonText);
              String signature = jsonObjs.getString("signature");
              return signature;
          }
      };
      OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
  3. Send the signed string on the client to the OSS server for authentication.
fig