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}
build.gradle, add the dependency:// app/build.gradledependencies {implementation 'com.tencent.cloud:clientattestation:latest.release'}
AndroidManifest.xml permissionsAndroidManifest.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" />
app/build.gradle file under defaultConfig:android {defaultConfig {ndk {abiFilters "armeabi-v7a", "arm64-v8a" // Optional armeabi-v7a or arm64-v8a}}}
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.**{*;}
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());}}
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 aboveimport com.tc.eo.clientattestation.ClientAttestation;// Start the client authentication engine.ClientAttestation.getInstance().start();
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}});
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.getAttestationToken() method provided by the SDK.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}
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());}}});}}
WebView for interactive authentication (and JS authentication)WebView (Android platform) is a key component for implementing these features.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.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.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.피드백