Follow

Integrate Shape Mobile SDK with Android App

Description

  • Instructions for integrating Shape Mobile SDK with Android applications

Return to Configuring Mobile Client (Mobile SDK Integration)

Return to Integrating Shape Defense

 

Environment

  • Shape Defense for Mobile
  • Android

Procedure

Step 1: Setup

1.0 Download Required Files

Download from the Shape Security section of the Silverline Portal:

  • The Mobile SDK library

  • A base configuration file for Android

mceclip1.png

 

1.1 Import Library

  1. Extract the zip file containing the Shape Mobile SDK.
  2. In the Binary directory, unzip APIGuard_Android_v41x.zip. It creates a directory named apiguard3-release.
  3. Copy this apiguard3-release directory and paste it under your Android project's libs directory.

1.2 Configure Gradle for Dependencies

In the app’s build.gradle, add the following dependencies:

dependencies {

implementation files('libs/apiguard3-release/apiguard3-release.aar')

implementation('com.squareup.okhttp3:okhttp:3.12.0')

implementation('androidx.localbroadcastmanager:localbroadcastmanager:1.0.0')

 

}

Note: OkHttp3 is always required because Shape Configuration Update requests use it. Mobile SDK supports OkHttp version 3.12 LTS and is compatible with 3.7, 3.10, 3.14, 4.3 and 4.9. Note that different OkHttp versions have different minimum Android API and Java version requirements.

 

1.3 Add Permissions

Include the following permissions that are required by the Mobile SDK to function properly. These permissions must not be removed at any time.

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

 

1.4 Exclude SDK from Obfuscation

Exclude the Shape library from any protection method that you normally use to protect your application (for example, DexGuard). Shape Mobile SDK for Android is already protected for obfuscation, optimization, and shrinking. No additional protection is needed. The AAR package includes ProGuard rules to preserve the symbols for Shape Library. 

When using DexGuard as an obfuscation tool, Mobile SDK 4.1 includes a new dexguard-rules.pro file that you can use to exclude Shape Libraries from obfuscation and optimization. Include the lines provided in this file in the app’s rules file for DexGuard.

Note: Obfuscation rules need to be updated every time you upgrade Shape artifacts.

 

1.5 Configure Settings for Native Libs

To make sure that the native libraries are included properly in the installed application, the following two steps need to be performed:

1. Add android:extractNativeLibs="true" in the AndroidManifest.xml file.

2. If the app is being packaged as Android App Bundle (AAB), add the following property in the gradle.properties file: android.bundle.enableUncompressedNativeLibs = false

 

Step 2: Initialize Mobile SDK

When the Mobile SDK library is available within the project, integrate Mobile SDK with your application. These are the basic steps, detailed below:

 

2.1 Add Import Statements

In your Application class, import:

  • com.apiguard3.APIGuard
  • com.apiguard3.APIGuard.InitializationCallback 

 

2.2 Create Mobile SDK Object

Create the Mobile SDK object as a member of the Application class.

private static final APIGuard apiGuard = new APIGuard();

 

2.2 Initialize SDK

In your Application class’s onCreate() method, call the initialize() method of the ApiGuard singleton object.

For more information about input parameters, see API Reference (link is below).

// this example looks for the file baseConfig.json in the res/raw directory of your application.

// this example uses "default" environment for updating the base configuration

APIGuard.getSharedInstance().initialize(this, this, R.raw.baseConfig, "default");

Note: If you broadcast push notifications to all or majority of app users at once, do not initialize Shape SDK in Application.onCreate(). Since Android OS calls Application.onCreate() when processing notifications, initialization in this callback would trigger a spike in Shape configuration requests. Instead, initialize Shape SDK in an activity onCreate(), which is executed only when the app is launched by the user and early in the application lifecycle (i.e. Splash Activity).

 

2.3 Implement APIGuard.InitializationCallback and Methods

Implement the Mobile SDK callback interface APIGuard.InitializationCallback and callback methods:

 

checkCertificates(List<Certificate> certificates, String host)

Mobile SDK calls this method when connection is being established to fetch the updated configuration from Shape Servers. If the certificate check fails, it throws an IOException. This function is used to implement cert pinning functionality for the configuration fetch endpoint. Shape recommends implementing this function for enhanced security.

 

log(String s)

Mobile SDK calls this method when it needs to log a message for debugging purposes. These messages are intended for developers; do not log them to the system log in production apps. Troubleshooting section (see link below) includes common error codes which are logged by Mobile SDK.

 

onInitializationSuccess()

This callback gets called on SDK initialization success. SDK will call this method on a background thread.

 

onInitializationFailure(String s)

This callback gets called if SDK initialization fails. The failure reason is passed as a string. This function is called on a background thread.

 

Complete Initialization Example

This code snippet shows a complete class definition that initializes Mobile SDK, incorporating all the steps in this procedure.

public class ExampleApplication extends Application implements APIGuard.InitializationCallback {

 

  @Override

  public void onCreate() {

      super.onCreate();

      initApiGuard();

  }

 

  public void initApiGuard() {

    // this example looks for the file apiguard.json in the Raw Folder of your application

    // this example uses "qa" environment for updating the base configuration

    APIGuard.getSharedInstance().initialize(this, this, R.raw.apiguard, "qa");

  }

 

  public void checkCertificates(List<Certificate> certificates, String host) throws

          IOException {

     // (Optional) Implement cert pinning functionality for the configuration fetch endpoint. 

// If the certificate check fails, it throws an IOException. 

}

 

  public void log(String message) {

    // Log messages for debugging purposes. Intended for developers.

    // Do not log to the system log in production apps.

  }

 

  public void onInitializationSuccess() {

    // Gets called if initialization for APIGuard is successful.

  }

 

  public void onInitializationFailure(String failureMessage) {

    // Gets called if initialization for APIGuard fails. The failure reason is passed as a string.

  }

}

 

Step 3: Request Decorating and Response Parsing

Decorating is the process of appending the Shape headers to the request. Before an API call is sent, the SDK must decorate each request object for protected endpoints.

In the class from which your app makes its network requests, add the following objects and calls:

  1. Call getRequestHeaders method with the APIGuard object. This call returns the telemetry payload as Map to be added to the network request as headers.
  2. Create an OkHttp Request object and add headers from the getRequestHeaders method. You may use onInitializationSuccess() callback or getState() to confirm that the APIGuard object is ready.
  3. Call OkHttpClient's execute method to get the response.
  4. Call the parseResponseHeaders method to have the SDK inspect the response headers and then use it for its internal functionality.

 

OkHttpClient client = new OkHttpClient.Builder().build();

 

Map<String, String> apiGuardHeaders = APIGuard.getSharedInstance()

.getRequestHeaders("https://someserver.com/post", null);

 

Request request = new Request.Builder()

     .url("https://someserver.com/post")

     .headers(Headers.of(apiGuardHeaders))

     .post(RequestBody.create(MediaType.parse("application/json"), ""))

     .build();

 

Response response = client.newCall(request).execute();

 

Map<String, String> responseHeaders = new HashMap<>();

 

for (String header : response.headers().names()) {

    responseHeaders.put(header, response.headers().get(header));

}

 

APIGuard.getSharedInstance().parseResponseHeaders(responseHeaders);

 

Step 4: Running your code

Once compiled and running, you should observe output from the log() callback. A successful SDK initialization will result in M0 being reported. M1 and M2 signify a successful configuration fetch. Any state which begins with “E” or “F” (e.g. E26), signifies an error. Not all errors are critical.

Please refer to the Troubleshooting Guide for Android SDK for explanations of some of the common error codes.

A properly integrated Shape SDK will result in protected requests being decorated with Shape headers. Shape headers will have the prefix of "guBJbWEZnL-". There may be one, seven, or eight headers with this prefix.

To validate that SDK has been integrated properly, follow these validation steps [LINK].

Related Content

Return to Configuring Mobile Client (Mobile SDK Integration)

Return to Integrating Shape Defense

 

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request