Android Integration
Overview
This section details the specific integration steps of the EdgeOne Client Authentication SDK in an Android project, including adding the SDK, configuring permissions, initialization, starting the authentication engine, handling challenges, and using tokens in API requests.
Integration steps
Note:
Before the integration is started, please ensure you have read and understood the Mobile Integration Overview to comprehend the basic authentication flow on mobile devices.
1. Add the EdgeOne SDK to your project.
Integrating the EdgeOne Client Authentication SDK into your Android project is the first step. You can import the SDK via Maven. Add the Maven source to your
setting.gradle or project build.gradle:// setting.gradle or project build.gradlerepositories {// Add the following maven configurationmaven { url 'https://repo.maven.com/' } // Example Maven source, please replace with the actual SDK-provided Maven source}
In your app module
build.gradle, add the dependency:// app/build.gradledependencies {implementation 'com.tencent.cloud:clientattestation:latest.release'}
2. Configure AndroidManifest.xml permissions
The SDK requires basic network access permissions during the authentication process. Please add the following permission declaration in your project's
AndroidManifest.xml file to ensure the SDK can perform network communications properly:<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
At the same time, to support certain native libraries within the SDK, you may need to configure the supported CPU architectures. Add the following in the
app/build.gradle file under defaultConfig:android {defaultConfig {ndk {abiFilters "armeabi-v7a", "arm64-v8a" // Optional armeabi-v7a or arm64-v8a}}}
If your project uses ProGuard for code obfuscation, add the following obfuscation rules to your ProGuard configuration file (typically
proguard-rules.pro) to prevent internal SDK classes from being obfuscated:-keep class com.**.TNative$aa { public *; }-keep class com.**.TNative$aa$bb { public *; }-keep class com.**.TNative$bb { *; }-keep class com.**.TNative$bb$I { *; }-keep class com.tcbas.**{*;}
3. Initialize the SDK
Before any authentication features are used, you need to initialize the EdgeOne SDK with your service domain and an optional log level. This operation is typically performed once in your
Application class or during application startup.import com.tcbas.common.framework.TCBas;import com.tcbas.common.framework.TCBasConfig;public class MyApplication extends Application {@Overridepublic void onCreate() {super.onCreate();// SDK initializationString baseUrl = "www.example.com"; // Set to the business domainTCBas.init(getApplicationContext(), new TCBasConfig.Builder().baseUrl(baseUrl).build());// Optional: Set the log level// TCBas.init(getApplicationContext(), new TCBasConfig.Builder()// .baseUrl(baseUrl)// .logLevel(LOG_LEVEL_DEBUG) // Optional. Set the log level// .build());// Optional: Set AndroidId// TCBas.init(getApplicationContext(), new TCBasConfig.Builder()// .baseUrl(baseUrl)// .logLevel(LOG_LEVEL_DEBUG) // Optional. Set the log level// .extraDataProvider(new ExtraDataProvider(){// @Override// public String getAndroidId() {// return super.getAndroidId();// }// })// .build());}}
Parameter description:
baseUrl: Your EdgeOne service domain, for example www.example.com.extraDataProvider: Optional parameter. Provide AndroidId to enhance risk identification capabilities.logLevel: Optional parameter used to control the log output level of the SDK. Optional values include:LOG_LEVEL_NONE: Disable logs (default)LOG_LEVEL_DEBUG: Enable logs at debug level and aboveLOG_LEVEL_INFO: Enable logs at info level and aboveLOG_LEVEL_WARN: Enable logs at warning level and aboveLOG_LEVEL_ERROR: Enable logs at error level and above4. Start the authentication engine
After initializing the SDK, you need to start the client authentication engine to enable the SDK to begin obtaining and managing authentication tokens. This operation starts the necessary background processes within the SDK.
import com.tc.eo.clientattestation.ClientAttestation;// Start the client authentication engine.ClientAttestation.getInstance().start();
Note: After the authentication engine is started, the SDK will be ready to handle authentication challenges and manage authentication tokens.
5. Execute the client authentication challenge
Authentication challenge is a key step in obtaining authentication tokens. This process involves obtaining the challenge ID and passing it to the SDK. The SDK will display necessary UI as needed (such as showing Captcha in
WebView) and compute the authentication token. This is accomplished through the attestWithParams() method provided by the SDK.import com.tc.eo.clientattestation.ClientAttestation;import com.tc.eo.clientattestation.AttestCallback;import com.tc.eo.clientattestation.AttestParams;import android.webkit.WebView;// attestId// Obtain from the console when actively initiating a challenge.// Obtain from the 'EO-Attest-Challenge' header field in the http response when challenges are passively initiated.String attestId = "your-attestId";AttestParams params = new AttestParams.Builder().attestId(attestId).webView(yourWebViewInstance) // WebView used to display the Captcha page; omit this parameter if Captcha is not required.reqTimeoutMillis(60000) // Optional, request timeout period, unit: milliseconds, default 60000 milliseconds.build();ClientAttestation.getInstance().attestWithParams(params, new AttestCallback() {@Overridepublic void onSuccess(String token) {// Return the risk token and place it in the 'EO-Attest-Token' header field of the http request.// For example: You can resend previously failed requests here with the new token.}@Overridepublic void onError(int errorCode, String msg) {// Error message callback// errorCode: error code// msg: error message}});
Parameter description:
attestId: Configure challenge ID, obtain from the console or returned in the request result.webView: Optional parameter, a WebView instance. This parameter must be provided when the authenticator requires user interaction (such as Captcha). If no UI interaction is required, the WebView can be hidden.captchaDisplayType: Optional parameter, the display mode for the interactive Captcha UI. Use CaptchaDisplayType.POPUP for pop-up full-screen display, and CaptchaDisplayType.FULL for embedded display in the page. Default value: CaptchaDisplayType.POPUP.reqTimeoutMillis: Optional parameter to set the request timeout period, unit: milliseconds, default 60000 milliseconds.6. Include the authentication token in the API request
When your Android application initiates API requests to backend services protected by EdgeOne, must include the attestation token in the request headers. You can obtain the currently valid attestation token at any time by calling the
getAttestationToken() method provided by the SDK.Note:
After each successful call to
attestWithParams(), the SDK generates or updates the attestation token. Before attaching the token to the request header, you must call getAttestationToken() again to obtain the latest token. Each time you need to use the token data, retrieve it again. Do not save or reuse the token data returned by getAttestationToken().// Obtain client authentication tokenString attestToken = ClientAttestation.getInstance().getAttestationToken();// Example: Add the token to your network request header// Assume you are using OkHttp or other networking librariesif (attestToken != null) {// OkHttp sample// Request originalRequest = new Request.Builder()// .url("https://your-backend-api.com/data")// .build();// Request.Builder requestBuilder = originalRequest.newBuilder();// requestBuilder.header("EO-Attest-Token", attestToken);// Request request = requestBuilder.build();// // Continue sending the request}
Important: Ensure this token is included in every API request that requires authentication. The SDK automatically manages the token life-cycle; you just need to retrieve the latest token before sending requests.
7. Handle server responses and challenges
When your backend service (protected by EdgeOne) receives a client request, it checks whether the request contains a valid attestation token. If authentication is required but no valid token is provided, the server returns an HTTP 428 status code, indicating that the client requires additional authentication. This is a critical step in Android client integration that requires active adaptation by developers.
Your Android application needs to implement a mechanism to capture and handle these HTTP 428 responses. For the specific handling process, refer to re-obtain the attestation token, or renew an expired attestation token (handling HTTP 428 challenges)
Here is a simplified sample for handling 428 challenges (using OkHttp as an example):
import okhttp3.Call;import okhttp3.Callback;import okhttp3.Headers;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;import java.io.IOException;import android.webkit.WebView;import com.tc.eo.clientattestation.ClientAttestation;import com.tc.eo.clientattestation.AttestCallback;import com.tc.eo.clientattestation.AttestParams;public class ApiClient {private OkHttpClient client = new OkHttpClient();private WebView webViewInstance; // Assuming you have a WebView instancepublic ApiClient(WebView webView) {this.webViewInstance = webView;}public void makeProtectedRequest(String url) {Request request = new Request.Builder().url(url).header("EO-Attest-Token", ClientAttestation.getInstance().getAttestationToken()).build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {// Handling network request failurese.printStackTrace();}@Overridepublic void onResponse(Call call, Response response) throws IOException {if (response.code() == 428) {Headers headers = response.headers();String challengeId = headers.get("EO-Attest-Challenge");if (challengeId != null) {// Received a 428 challenge, perform authenticationAttestParams params = new AttestParams.Builder().attestId(challengeId).webView(webViewInstance) // Pass the WebView instance.build();ClientAttestation.getInstance().attestWithParams(params, new AttestCallback() {@Overridepublic void onSuccess(String token) {// Authentication successful, resend the requestmakeProtectedRequest(url); // Resend the original request}@Overridepublic void onError(int errorCode, String msg) {// Authentication failedSystem.err.println("Authentication failed: " + msg);}});} else {System.err.println("EO-Attest-Challenge header not found in 428 response");}} else if (response.isSuccessful()) {// Request successful, process business dataSystem.out.println("Request successful: " + response.body().string());} else {// Handle other HTTP errorsSystem.err.println("Request failed: " + response.code() + " " + response.message());}}});}}
8. Optional: Use WebView for interactive authentication (and JS authentication)
In some client authentication scenarios, the authenticator may require user interaction (for example: interactive Captcha) or perform computationally intensive tasks (for example: cryptographic proof of work). At this point, the EdgeOne SDK requires specific runtime environment support. On mobile platforms,
WebView (Android platform) is a key component for implementing these features.When the authenticator requires rendering an interactive CAPTCHA or running a JavaScript-based cryptographic Proof-of-Work challenge, the SDK requires a
WebView instance to be provided when the attestWithParams() method is called. This means developers must pre-allocate a WebView instance in the application and pass it as a parameter to the SDK when invoking the authentication API.Interactive authentication scenarios
Some authenticators (such as TC-CAPTCHA using embedded or pop-up interactive settings) require a
WebView instance to render their interactive interface. This WebView instance will display the CAPTCHA page within the application, thus requiring pre-configuration to ensure proper display.Embedded Interactive Authentication: The CAPTCHA interface is displayed as a fixed block on the device screen. To ensure correct UI rendering without compromising user experience, developers must preset the size, stacking order, and alignment of the rendering window. Note that the embedded authentication GUI does not scale with the screen view. For example, TC-CAPTCHA embedded mode recommends reserving at least 300x230 pixels for optimal rendering and user interaction.
Pop-up Interactive Authentication: The CAPTCHA interface appears as a floating window on the device screen when authentication is invoked. Similar to embedded authentication, the size, stacking order, and alignment of the rendering window need to be preset. The characteristic of pop-up authentication is that when the screen view is smaller than a specific threshold, the pop-up authentication GUI automatically scales to adapt to different screen sizes. For example, the initial rendering block size for TC-CAPTCHA pop-up mode is 360x360 pixels.
JavaScript-based authentication scenarios
Some authenticators (such as TC-CAPTCHA using invisible mode) require a
WebView instance as a JavaScript runtime environment, primarily for executing cryptographic Proof-of-Work (PoW) challenges. In this scenario, the WebView instance only provides a JavaScript execution sandbox and does not visibly render any UI. Therefore, the passed WebView instance does not need to be visible, and the SDK will not use it for UI rendering.- Overview
- Integration steps
- 1. Add the EdgeOne SDK to your project.
- 2. Configure AndroidManifest.xml permissions
- 3. Initialize the SDK
- 4. Start the authentication engine
- 5. Execute the client authentication challenge
- 6. Include the authentication token in the API request
- 7. Handle server responses and challenges
- 8. Optional: Use WebView for interactive authentication (and JS authentication)