tencent cloud

문서Tencent Cloud EdgeOne

Android Integration

Download
포커스 모드
폰트 크기
마지막 업데이트 시간: 2026-04-23 16:52:56

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.gradle
repositories {
// Add the following maven configuration
maven { 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.gradle
dependencies {
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 {
@Override
public void onCreate() {
super.onCreate();
// SDK initialization
String baseUrl = "www.example.com"; // Set to the business domain
TCBas.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 above
LOG_LEVEL_INFO: Enable logs at info level and above
LOG_LEVEL_WARN: Enable logs at warning level and above
LOG_LEVEL_ERROR: Enable logs at error level and above

4. 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() {
@Override
public 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.
}

@Override
public 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 token
String attestToken = ClientAttestation.getInstance().getAttestationToken();

// Example: Add the token to your network request header
// Assume you are using OkHttp or other networking libraries
if (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 instance

public 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() {
@Override
public void onFailure(Call call, IOException e) {
// Handling network request failures
e.printStackTrace();
}

@Override
public 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 authentication
AttestParams params = new AttestParams.Builder()
.attestId(challengeId)
.webView(webViewInstance) // Pass the WebView instance
.build();

ClientAttestation.getInstance().attestWithParams(params, new AttestCallback() {
@Override
public void onSuccess(String token) {
// Authentication successful, resend the request
makeProtectedRequest(url); // Resend the original request
}

@Override
public void onError(int errorCode, String msg) {
// Authentication failed
System.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 data
System.out.println("Request successful: " + response.body().string());
} else {
// Handle other HTTP errors
System.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.

도움말 및 지원

문제 해결에 도움이 되었나요?

피드백