This topic describes how to integrate the Anti-Bot SDK into Android apps. In this topic, Anti-Bot SDK is referred to as SDK. Before you can enable the app protection feature for your Android apps, you must integrate the SDK into your Android apps.

Limits

Your Android apps use Android 16 or later. If the API version is earlier than 16, the SDK cannot work as expected.

Prerequisites

  • The app protection feature is purchased and enabled.

    For more information, see Procedure to enable app protection.

  • The SDK for Android apps is obtained.

    After you purchase the app protection feature, you can contact technical support in the DingTalk service group to obtain the SDK. You can also submit a ticket to obtain the SDK.

    The SDK for Android apps contains an AAR file, which is named in the following format: AliTigerTally_X.X.X.aar. X.X.X indicates the version number of the file.

  • The SDK authentication key, namely the app key, is obtained.
    To obtain the app key, log on to the Web Application Firewall console and choose Protection Settings > Website Protection. On the Bot Management tab of the Website Protection page, turn on App Protection and click Obtain and Copy Appkey. The SDK authentication key is used in the integration code to initiate an SDK initialization request.
    Note The app key obtained for all domain names in the current Alibaba Cloud account is the same and unique, regardless of whether you integrate the SDK into Android apps or iOS apps.
    App Protection
    Authentication key example:
    ****OpKLvM6zliu6KopyHIhmneb_****u4ekci2W8i6F9vrgpEezqAzEzj2ANrVUhvAXMwYzgY_****vc51aEQlRovkRoUhRlVsf4IzO9dZp6nN_****Wz8pk2TDLuMo4pVIQvGaxH3vrsnSQiK****

Background information

The SDK is used to sign requests that are sent by apps. Web Application Firewall (WAF) verifies the signatures in the requests to identify risks in app services and block malicious requests.

(Optional) Create a test Android project

You can integrate the SDK into a real Android project. You can also integrate the SDK into a test Android project to familiarize yourself with the integration operations before you integrate the SDK into a real Android project.

The following example shows how to use Android Studio to create a test Android project.

The following figure shows a test project named TigerTally_sdk_test. Test projectBefore you integrate the SDK into apps, make sure that the test project runs as expected. Check whether the test project is running

Procedure

  1. Use Android Studio to open the test project and enter the file directory.
  2. Reference the AAR file.
    1. Copy the AliTigerTally.aar file to the libs directory. You can also drag the file to the directory. Copy the file to the libs directory
    2. Open the build.gradle file and modify the configurations based on the following descriptions:
      • Add the libs directory as a source of dependencies.
        repositories{
           flatDir {
             dirs 'libs'
           }
        }
      • Add a compilation dependency.
        Notice You must replace the version number (X.X.X) in the following code with the version number of the AAR file that you obtain.
        dependencies {
          compile(name: 'AliTigerTally_X.X.X', ext: 'aar')
        }
    3. Click Sync Now to synchronize the modifications to the project.
  3. Optional:Reference the SO file. If the SO file is included in the project, skip this step. Otherwise, add the following configuration to the build.gradle file:
    android {
        defaultConfig {
        ndk {
            abiFilters 'arm64-v8a', 'x86', "armeabi-v7a"
            //abiFilters "armeabi-v7a"
          }
        }
    }
  4. Apply for the following permissions for apps.
    Permission Required Description
    android.permission.INTERNET Yes Connects to the Internet.
    android.permission.ACCESS_NETWORK_STATE No Obtains the network status of a device.
    android.permission.ACCESS_WIFI_STATE No Obtains the Wi-Fi connection status of a device.
    android.permission.READ_PHONE_STATE No Reads the status and identity of a device.
    Note You must dynamically apply for this permission for Android 6.0 or later.
    android.permission.BLUETOOTH No Obtains the Bluetooth permissions of a device.
    android.permission. READ_EXTERNAL_STORAGE No Reads the external storage of a device.
    Note You must dynamically apply for this permission for Android 6.0 or later.
    android.permission.CHANGE_NETWORK_STATE No Changes the network status of a device.
  5. Add the integration code.
    1. Specify a user ID.
      Function:
      int setAccount(String account);

      Description: configures a user ID in requests. This way, you can configure WAF protection policies in a more efficient manner.

      Parameter: <account>, which specifies the user ID. Data type: string. We recommend that you enter a masked user ID.

      Return value: A value that indicates whether the setting is successful. Data type: int. The value 0 indicates that the setting is successful. The value -1 indicates that the setting failed.

      Sample code:
      final String account="user001";
      TigerTallyAPI.setAccount(account); // If the logon user is a guest, you do not need to call this function. You can directly call the initialization function. 
    2. Initialize the SDK.
      Function:
      int init(Context context, String appkey, int type);

      Description: initializes the SDK and performs one-time information collection. One-time information collection allows you to collect terminal information for one time. If you want to collect terminal information again, call the init function.

      Parameters:
      • <context>: specifies the context that is passed to the apps. The context is the global information about the app environment in Android.
      • <appkey>: specifies the SDK authentication key. Data type: string.
      • <type>: specifies the initialization type. Data type: int. The value is fixed to 1, which indicates that the default initialization type is used.

      Return value: A value that indicates whether the initialization is successful. Data type: int. The value 0 indicates that the initialization is successful. The value -1 indicates that the initialization failed.

      Sample code:
      final String appkey="****OpKLvM6zliu6KopyHIhmneb_****u4ekci2W8i6F9vrgpEezqAzEzj2ANrVUhvAXMwYzgY_****vc51aEQlRovkRoUhRlVsf4IzO9dZp6nN_****Wz8pk2TDLuMo4pVIQvGaxH3vrsnSQiK****";
      int ret = TigerTallyAPI.init(getApplicationContext(), appkey, 1); // If the value of ret is 0, the initialization is successful. 
      Log.d("AliSDK", "ret:" + ret);
    3. Sign request data.
      Function:
      String vmpSign(int signType, byte[] input);

      Description: signs the input data and returns the signature string.

      Parameters:
      • <signType>: specifies the signature algorithm. Data type: int. The value is fixed to 1, which indicates that the default signature algorithm is used.
      • <input>: specifies the data to be signed. Data type: byte[].

        In most cases, the data to be signed is the entire body of a request. If the POST request body is empty or a GET request body is used, enter null or a byte[] array that is converted from an empty string. Example: "".getBytes("UTF-8").

      Return value: The signature string is returned. Data type: string.

      Sample code:
      Note In the following sample code, the signature string is defined as wToken.
      String request_body = "i am the request body, encrypted or not!";
      String wToken = null;
      try {
          wToken = TigerTallyAPI.vmpSign(1, request_body.getBytes("UTF-8"));
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      Log.d("AliSDK", "wToken:" + wToken);
    4. Add the signature string to the HTTP header.
      For example, if your project uses the HttpURLConnection class, you can add the content of the signature string wToken to the objects of the HttpURLConnection class.
      Sample code:
      String request_body = "i am the request body, encrypted or not!";
      new Thread(new Runnable() {
          @Override
          public void run() {
              try {
                  URL url = new URL("https://www.aliyundoc.com");
                  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                  conn.setReadTimeout(5000);
                  conn.setRequestMethod("POST");
                  // set wToken info to header
                  conn.setRequestProperty("wToken", wToken);
                  OutputStream os = conn.getOutputStream();
                  // set request body info
                  byte[] requestBody = request_body.getBytes("UTF-8");
                  os.write(requestBody);
                  os.flush();
                  os.close();
                  int code = conn.getResponseCode();
                  Log.d("respCode", Integer.toString(code));
              } catch (MalformedURLException e) {
                  e.printStackTrace();
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
              } catch (ProtocolException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          };
          }).start();
    5. Send requests that use the new HTTP header to the server of apps.
      WAF receives requests that are destined for the server, parses the signature string wToken to identify and block malicious requests, and then forwards normal requests to the server.

Obfuscate code

If you use ProGuard to obfuscate code, you can use -keep to configure the functions of the SDK.

Sample code:
-keep class com.aliyun.TigerTally.* {*;}