Skip to navigation

Native (advanced implementation)

Learn how to integrate the mobile SDK with your native iOS or Android app using our advanced implementation.

This guide is relevant for the current Mobile SDK. While we highly recommend using the latest version, if you are using a legacy integration, refer to the iOS or Android documentation.

After you add the SDK to your project, you need to start the SDK and integrate with Bot Defender, Account Defender, or both. You can learn how to do so with this guide.

This guide covers the advanced implementation for native apps. If you need another implementation method, see our other guides:

ImplementationDetails
Native (recommended implementation
  • Fast integration with minimal points.
  • SDK intercepts your URL requests.
  • Handles blocked requests.
  • Not recommended if you need to retry requests after solving challenges.
  • Not recommended if you use advanced URLSession features (authentication challenges, caching, etc.).
Native (basic implementation)
  • Few integration points.
  • SDK does not intercept URL requests.
  • Handles blocked requests.
  • Notifies when a challenge is solved or cancelled; great for analytics and logs.
  • Not recommended for retrying requests after challenges.
  • Not recommended as a trigger for resending URL requests.
Native (advanced functionality)
  • SDK intercepts URL requests.
  • Handles blocked requests with challenge results (solved/canceled); great for analytics, logs, and resending URL requests.
  • Option to automatically retry blocked requests after challenges.
  • Recommended if you need to retry requests after challenges.
  • Not recommended if you use advanced URLSession features.

Prerequisites

  • Admin access to the HUMAN Console, which you’ll need to:
    • Retrieve your Application ID. You can find this by navigating to Platform Settings > Applications and copying the ID. If you need to use multiple IDs, see Handle multiple Application IDs.
    • Set the token expiration and validity.
  • An integrated HUMAN Enforcer that is enabled and in active blocking mode. Refer to our Enforcer guides for more information.
  • Android: Requires your app to use OkHttp, which supports Interceptors.
  • iOS: Requires your app to use URLSession or any third-party library based on it.

Start the SDK

When starting the SDK, keep the following in mind:

  1. Start the SDK as soon as possible in your app’s flow. We recommend doing so in the Application’s onCreate function in Android or the AppDelegate’s didFinishLaunchingWithOptions function in iOS. If you don’t do this, then your application may send a URL request to your server before the SDK starts. This means the request will not include HTTP headers that indicate whether the request is legitimate, and as a result:
    • The Enforcer may block the request instead, and
    • The SDK will not be able to present a challenge to the user
  2. Start the SDK on the main thread.
  3. Specify which domains the SDK should intercept. If none are specified, all domains will be intercepted. The SDK checks if the URL ends with one of the specified domains. For example, if you set example.com, the SDK intercepts calls to both www.example.com and api.example.com.

Below are example implementations for both Android and iOS:

Don’t forget to replace <APP_ID> with your actual Application ID.

import android.app.Application
import com.humansecurity.mobile_sdk.HumanSecurity
import com.humansecurity.mobile_sdk.main.policy.HSPolicy
import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startHumanSDK()
}
private fun startHumanSDK() {
try {
val policy = HSPolicy().apply {
automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorType.INTERCEPT_WITH_DELAYED_RESPONSE // or INTERCEPT_AND_RETRY_REQUEST
automaticInterceptorPolicy.setInterceptedDomains(setOf("example.com"), "<APP_ID>")
}
HumanSecurity.start(this, "<APP_ID>", policy)
} catch (exception: Exception) {
println("Exception: ${exception.message}")
}
}
}

In particular, note the following:

  1. Initialization: We start the SDK as early as possible on the main thread to ensure all URL requests include the necessary HTTP headers.
  2. Policy Configuration: We create an HSPolicy instance to configure the SDK’s behavior. In this case:
    • We set the automaticInterceptorPolicy.interceptorType to INTERCEPT_WITH_DELAYED_RESPONSE or INTERCEPT_AND_RETRY_REQUEST to enable the Automatic Interception feature.
    • We specify the domains your app will interact with.
  3. Starting the SDK: We call the HumanSecurity.start(appId:policy:) function with the following parameters:
    • The Application instance (Android only)
    • Your Application ID. If you have multiple IDs, see our guide on how to handle them.
    • The HSPolicy object that we configured

Integrate with Bot Defender

1

Add SDK’s HTTP Headers to your URL requests

  1. Disable the request timeout so the call can wait until the challenge finishes. On iOS, set timeoutInterval to 0. On Android, set the OkHttp call timeout to 0, or the Ktor request timeout to infinite, and configure connectTimeout and the read/write timeouts as needed. Set HSAutomaticInterceptorPolicy.urlSessionRequestTimeout when starting the SDK on iOS. That value is the timeout for the request the SDK sends.
  2. Send the URL request through the SDK. On Android, add HSInterceptor as the last interceptor. The SDK adds its HTTP headers to the request and keeps the token in those headers up to date. Do not cache the headers.
  3. If Bot Defender blocks the request, the SDK presents a challenge and holds the call until the challenge ends.
  4. When interceptorType is INTERCEPT_AND_RETRY_REQUEST and the challenge is solved, the SDK resends the request once before your handler runs. That retry can also be blocked, and the SDK does not send it again. A canceled challenge is not resent.
  5. Your request handler then receives the result. On Android, check errorType for CHALLENGE_WAS_SOLVED or CHALLENGE_WAS_CANCELLED. On iOS, check errorType for challengeWasSolved or challengeWasCancelled. After a retry, the handler receives the second response instead of the solved error.

Below are example implementations for both Android and iOS:

These examples use OkHttp or Ktor and add HSInterceptor as the last interceptor.

import com.humansecurity.mobile_sdk.HumanSecurity
import com.humansecurity.mobile_sdk.main.HSBotDefenderErrorType
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit
class MyHttpClient {
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.callTimeout(0, TimeUnit.SECONDS)
.addInterceptor(HSInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
.build()
fun sendRequest(url: String) {
try {
val request: Request = Request.Builder().url(url).build()
okHttpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
response.body?.string()?.let { responseBody ->
when (HumanSecurity.BD.errorType(responseBody)) {
HSBotDefenderErrorType.CHALLENGE_WAS_SOLVED -> {
println("Challenge was solved")
}
HSBotDefenderErrorType.CHALLENGE_WAS_CANCELLED -> {
println("Challenge was cancelled")
}
else -> {
println("Unknown error")
}
}
}
}
}
} catch (exception: Exception) {
println("Request failed. Exception: $exception")
}
}
}
2

Handle blocked requests

When the Enforcer blocks a request, it returns a JSON string in the response body with an HTTP status code of 403, which includes metadata for the SDK. For example:

{
"vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
"appId": "PXj9y4Q8Em",
"action": "captcha",
"collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
}

Your app should pass the entire JSON response to the SDK via the HSBotDefender/handleResponse(response:data:callback:) function. If not, the SDK won’t present a challenge to the user. When handling blocked requests:

  • Treat blocked requests as a failure. After the challenge is solved:
    • You may resend the request
    • If the request was triggered by a user’s action, inform the user that they can retry the same action. For example, if the user was attempting to access a certain page before the challenge, then when they return to that same page after solving the challenge, you may want to show a message indicating that they can now continue on to that page.
  • Use the handler callback to log analytics, create logs, and so on.
  • (Optional) Use the handler callback to retry the original request when appropriate. Consider the following:
    • Callback scope: The callback is called outside the original request’s scope. Ensure your app handles this correctly.
    • Challenge cancellation: If the challenge is canceled by the user. Do not retry the request to avoid it being blocked again.
    • Retry block possibility: The retry attempt may also be blocked. Do not assume it will succeed.
3

Set custom parameters (optional)

Custom parameters are additional custom values that you can set yourself to enrich the data you receive from HUMAN. You can have up to 10 custom parameters, and they must follow the pattern custom_paramN, where N is a number between 1 and 10. To set custom parameters:

  • Android: Use a HashMap<String, String>.
  • iOS: Use a Dictionary<String, String>.

Call HSBotDefender.setCustomParameters(parameters:forAppId:) only after the HumanSecurity.start(appId:policy:) function has been called.

Below are example implementations for both Android and iOS:

import com.humansecurity.mobile_sdk.HumanSecurity
fun setCustomParametersForBotDefender() {
try {
val customParameters = HashMap<String, String>().apply {
put("custom_param1", "hello")
put("custom_param2", "world")
}
HumanSecurity.BD.setCustomParameters(customParameters, "<APP_ID>")
} catch (exception: Exception) {
println("Exception: ${exception.message}")
}
}

Integrate with Account Defender

1

Enable Account Defender in your app

To enable Account Defender, set the UserID of your current logged-in user in the SDK. Below are example implementations for both Android and iOS:

import com.humansecurity.mobile_sdk.HumanSecurity
fun onUserLoggedIn(userID: String) {
try {
HumanSecurity.AD.setUserId(userID, "<APP_ID>")
} catch (exception: Exception) {
println("Exception: ${exception.message}")
}
}
2

Notify HUMAN's backend on outgoing URL requests from the app

For Account Defender to protect the user’s account, your app has to provide the SDK with outgoing URL requests. While the SDK’s interceptor is enabled, the SDK collects your outgoing URL requests automatically. You do not need to manually call the SDK’s API to collect these requests.

Below are example implementations for both Android and iOS:

import com.humansecurity.mobile_sdk.HumanSecurity
import okhttp3.Interceptor
import okhttp3.Response
class AccountDefenderInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
try {
HumanSecurity.AD.registerOutgoingUrlRequest(request.url.toString(), "<APP_ID>")
} catch (exception: Exception) {
println("Exception: ${exception.message}")
}
return chain.proceed(request)
}
}
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MyHttpClient {
private final OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new AccountDefenderInterceptor())
.build();
void sendRequest(String url) {
Runnable r = () -> {
try {
Request request = new Request.Builder().url(url).build();
Response response = httpClient.newCall(request).execute();
// Handle the response...
} catch (Exception exception) {
Log.i("MyHttpClient", "Request failed. Exception: " + exception);
}
};
new Thread(r).start();
}
}
3

Set additional data (optional)

Additional data are additional custom values that you can set yourself to enrich the data you receive from HUMAN. Note that these are separate from custom parameters and are unique to Account Defender. Additional data must follow the pattern my_keyN, where N is a number. To set additional data:

  • Android: Use a HashMap<String, String>
  • iOS: Use a Dictionary<String, String>

Call the HSAccountDefender/setAdditionalData(parameters:forAppId:) only after the HumanSecurity/start(appId:policy:) function has been called.

Below are example implementations for both Android and iOS:

import com.humansecurity.mobile_sdk.HumanSecurity
fun setAdditionalDataForAccountDefender() {
try {
val additionalData = HashMap<String, String>().apply {
put("my_key1", "hello")
put("my_key2", "world")
}
HumanSecurity.AD.setAdditionalData(additionalData, "<APP_ID>")
} catch (exception: Exception) {
println("Exception: ${exception.message}")
}
}