Android SDK

This guide describes how to integrate the DataDome SDK in your Android application.

The DataDome Android SDK is a lightweight library written in Java. It assumes the following roles once integrated into your app:

  • Intercepting and handling responses protected by DataDome. A challenge is displayed by the SDK, and once the challenge is validated, pending requests are automatically retried. The challenge page includes captcha and device check
  • Managing cookies in the app. The DataDome cookie is a session token updated every request. The SDK stores and signs automatically all requests with the DataDome cookie.
  • Collecting behavioral signals in the app to understand how users use your app. Those collected data improve our detection using ML models. Please refer to this section for more information on what piece of data we collect in your app.

Install the SDK

Compatibility

DataDome Android SDK is compatible with Android 16+

Gradle dependency

DataDome Android SDK is available on Maven Central. To get the SDK integrated in your project, follow the steps below:

In your build.gradle in the root:

allprojects {
    repositories {
        mavenCentral()
    }
}

build.gradle in the module, according to the version of the SDK you need, we usually recommend you to use the latest version:

dependencies {
    implementation 'co.datadome.sdk:sdk:1.+'
}

Configure the SDK

Initialization

First of all, you need to initialize the SDK with the builder.

import android.app.Application;

class MainActivity extends AppCompatActivity {

    private DataDomeSDK.Builder dataDomeSDK;

    public void makeRequest(){
      	dataDomeSDK = DataDomeSDK.with(getApplication(), "Client_Side_Key", BuildConfig.VERSION_NAME)

    }

    [...]
    
}

It is possible to customize some parameters of the SDK, using the Builder:

  • Mandatory: .with(Application application, String dataDomeSDKKey, String appVersion): create a new Builder

  • optional: .listener(DataDomeSDKListener listener): set the DataDomeSDKListener associated with the SDK instance. It defines the response page's status.

  • optional:.agent(String userAgent): set a custom User Agent that will be used for event tracking

  • optional:.bypassAcceptHeader(Boolean bypassAcceptHeader): Do not use this option if you don't need to specify a custom Accept header
    Set to true to bypass the DataDome Accept header (For more informations, please read Optional Settings)

  • optional:.backBehaviour(BackBehaviour behaviour): set a custom behavior for the back action on the Captcha page. BackBehaviour options are:

    • GO_BACKGROUND (default one): the Back button makes your app move to the background. Users can't go back if they don't pass the Captcha test (recommended)
    • BLOCKED: the Back button has no effect. Users can't go back if they don't pass the Captcha test
    • GO_BACK: the Back button makes the app go back and cancel the call
  • optional:.activateDatadomeLogger(true): enable a verbose logger for more details. See verbose logger activation verbose logger

  • optional: .setResponsePageLanguage(String language): customize the DataDome response pages language. response page language

Add your DataDome Client-Side Key to your project

SDK initialization needs your client_key that figures in your dashboard. If the key is missing, the SDK will throw an exception with the following log:
[DataDome] Missing DataDome client key.

Interception

The DataDome Android SDK interception process depends on your network dependencies.

If you are using Okhttp network, please follow the Okhttp integration process: okhttp-integration documentation

If for some reasons you prefer to control the responses validation or not to use Okhttp library, here is the manual integration process: manual-integration documentation

Mobile signals usage

To enhance the precision of our detection models, DataDome collects minimal data from users. The collected data does not include personal information such as users’ name, email address, credentials, phone number, payment information, form information, etc. Those data does not include International Mobile Equipment Identity (IMEI) or any personally identifiable information (PII) as well.

Any data collected is stored using high-performing security standards.
To learn more about DataDome privacy practices, we invite you to check DataDome Privacy Policy.

We provide 2 event tracking types:

  • Touch screen tracking
  • Custom event tracking

Touch Screen Event tracking

The gesture events tracking in Android are detectable through the exposed view and we get gestures through the dispatchTouchEvent method. To implement this functionality, please refer to the following API:

@Override
  public boolean dispatchTouchEvent(MotionEvent event) {
    dataDomeSDK.handleTouchEvent(event);
    return super.dispatchTouchEvent(event);
}

Custom event Tracking

Collecting static device and application minimal identification data. Those informations include screen size, device model, application release version and captcha resolve status.

Share cookies between your mobile app and your WebViews

If you are using webviews in your application to display web pages that are protected with DataDome, you need to share the cookie between the HTTP client instances of mobile app and the web pages, therefore a second Captcha won't be required on the web-based part of the app.

To share the DataDome cookie from the SDK to your webview instance, use the following API:

String cookie = dataDomeSdk.getCookie();
CookieManager.getInstance().setCookie(domain,"datadome="+cookie);
// your webview code
webview.loadUrl(url);

The getCookie API returns the last stored DataDome cookie value. We need to set this value to the webview CookieManager.
The getCookie method returns only the value of the cookie. If for some reasons, you need the DataDome cookie with all its attributes, use getCookieWithAttributes

To share the DataDome cookie from the webview instance to mobile app, you need to store the latest webview cookie, use the setCookie(cookie) API:

// Get webview cookies
String cookies = CookieManager.getInstance().getCookie(url);

// If your webview has other cookies than the DataDome cookie, you can filter the DataDome cookie calling filterDatadomeCookie method as below
//    String datadomeCookie = DataDomeUtils.filterDatadomeCookie(cookies);

// store DataDome cookie
dataDomeSdk.setCookie(datadomeCookie);

filterDatadomeCookie method filter on DataDome cookie and is helpful when your CookieManager returns a string with other non-datadome cookies value. It can be implemented as below:

private String filterDatadomeCookie(String cookie) {
  String cookieName = "datadome=";
  String[] cookieSplit = cookie.split(cookieName);
  if (cookieSplit.length > 1) {
    if (cookieSplit[1].contains(";")) {
      return cookieName+cookieSplit[1].split(";")[0];
    }
    return cookieName+cookieSplit[1];
  }
  return "";
}

Use the Logger (Optional)

Added in version 1.7.0

Starting from DataDome Android SDK v1.7.0 you can enable a verbose logger to get more details about SDK response validation process. This feature is optional and can be activated/ deactivated at DataDome SDK initialization.
The DatadomeLogger enabler helps to track extra process details (captcha loading URL, cookie storage value, retried request responses, etc). Note that SDK main logs remain printed even if DatadomeLogger is disabled.

dataDomeSDK = DataDomeSDK
            .with(getApplication(), "Client_Side_Key", BuildConfig.VERSION_NAME)
            .activateDatadomeLogger(true) // Add this line to enable DatadomeLogger

Set the language of the DataDome response pages (Optional)

Added in version 1.11.0

The SDK is in charge of displaying the DataDome response pages when needed. Those response pages come in the form of a Captcha page, a Hard Block page or a Device Check page.

By default this page language is the application language (if supported, see the list of supported languages)

Starting from the Android SDK version 1.11.0, if you prefer to customize the language of those pages, you can do so by calling the setResponsePageLanguage(String language) method of DataDomeSDK with a language code (as define in the RFC 7231 section 5.3.5)

DataDomeSDK.setResponsePageLanguage("fr")

Usage

Traffic interception

Depending on the networking layer you setup for your application, choose one or multiple integrations from the list below:

The default and recommended integration is with the OkHttp Client interceptor:

Manual integration is also available:

Use custom Accept header

By default, the DataDome SDK overrides the default Accept header for each API call to JSON.
Please follow the 2 steps below to change this behavior:

1 - Inside the Mobile app

Set the 4th parameter to true during Interceptor instantiation.

import android.app.Application;

class MainActivity extends AppCompatActivity {

    private DataDomeSDK.Builder dataDomeSDK;

    public void makeRequest(){

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.addInterceptor(new DataDomeInterceptor(getApplication(), dataDomeSDKListener, "Client_Side_Key", BuildConfig.VERSION_NAME, true));
        OkHttpClient client = builder.build();
    }

    [...]
}

2 - DataDome Dashboard

Force the response format inside the mobile app endpoint settings to JSON.

Force a Captcha display

You can simulate a Captcha display using the framework by providing a user agent with the value BLOCKUA.
You can set the User-agent header value in your OkHttp request builder:

Request request = Request.newBuilder()
                    .header("User-Agent", "BLOCKUA")
                    .url(url)
                    .build();

IMPORTANT NOTE
Make sure the BLOCKUA user agent is not used in production. Otherwise, the Captcha will appear at least once for each user.

CookieJar compatibility

CookieJar is an API used to provide policy and persistence for HTTP cookies.
Implementing the CookieJar interface allows a better control over cookie update and storage, therefore, it overrides the DataDome cookie resulting of challenge resolution. This cookie is injected in the failed requests retry and its override in the retried requests can potentially lead to a captcha infinite loop. To avoid this, please follow those recommended setups:

CookieJar interface implementation

If you are implementing the CookieJar interface, it is recommended to integrate the DataDomeCookieJar. You can do this by passing your CookieJar implementation as a parameter, using the following code snippet:

// Integrating DataDomeCookieJar with your CookieJar instance as parameter
builder.cookieJar(dataDomeInterceptor.getDataDomeCookieJar(cookieJar))

Alternatively, you can explicitly set the DataDome cookie value by calling dataDomeSdk.getCookie() in the loadForRequest method of your CookieJar implementation. This method returns the cookies for outgoing HTTP requests. Here's an example of how this can be done:

@NonNull
@Override
public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
  List<Cookie> cacheCookies;
  cacheCookies = cookieStore.get(url.toString());
  String datadomeCookie = dataDomeSdkInstance.getCookieWithAttributes();
  if(datadomeCookie !=  null && !datadomeCookie.isEmpty()) {
    cacheCookies.add(Cookie.parse(url, datadomeCookie)));
  }
  return cacheCookies != null ? cacheCookies : new ArrayList<>();
}

Third party library CookieJar

This integration supports both custom CookieJar implementation and third party libraries such as PersistentCookieJar.
Please follow the code below for third party libraries usage.

// PersistentCookieJar instance
val cookieJar: ClearableCookieJar =
            PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(context))
// Integrating DataDomeCookieJar with the PersistentCookieJar instance as parameter 
builder.cookieJar(dataDomeInterceptor.getDataDomeCookieJar(cookieJar))

Sample app

Below is a sample app demonstrating the implementation of DataDomeSDK in a basic Java application.

https://github.com/DataDome/datadome-android-SDK-sample/