Native - Advanced Functionality

Integrating the SDK into Your Native iOS/Android App

Introduction

In this article, we will learn how to integrate the SDK into your native iOS or Android app.

Highlights

  • Handle Blocked Requests with Challenge Results:
    • Benefits:
      • Great for analytics, logs, etc.
      • Enables sending the URL request again.
  • Automatic Retry Option:
    • Option to retry the blocked request automatically after the challenge is solved.
  • URL Request Interception:
    • The SDK intercepts your URL requests.

Notes:

  • 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.

Topics Covered

  • How to Start the SDK
  • Bot Defender Integration
    • Adding SDK’s HTTP headers to your URL requests
    • Presenting a challenge to the user
    • Handling the challenge’s result
    • Setting custom parameters (optional)
  • Account Defender Integration
    • Enabling Account Defender
    • Notifying HUMAN’s backend on outgoing URL requests
    • Setting additional data (optional)

How to Start the SDK

  • Initialize Early: Start the SDK as soon as possible in your app’s lifecycle to ensure all URL requests include the SDK’s HTTP headers. Delaying SDK initialization may result in requests being blocked by HUMAN’s Enforcer.
    • Android: Initialize in the Application’s onCreate method.
    • iOS: Initialize in the AppDelegate’s didFinishLaunchingWithOptions method.
  • Main Thread: Start the SDK on the main thread.
  • Domain Specification: Specify which domains the SDK should intercept. If no domains are specified, all domains will be intercepted. The SDK checks if the URL’s domain ends with one of the specified domains (e.g., setting example.com will also intercept www.example.com and api.example.com).

Example Implementation

Android

Kotlin:

1import android.app.Application
2import com.humansecurity.mobile_sdk.HumanSecurity
3import com.humansecurity.mobile_sdk.main.policy.HSPolicy
4import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType
5
6class MainApplication : Application() {
7
8 override fun onCreate() {
9 super.onCreate()
10 startHumanSDK()
11 }
12
13 private fun startHumanSDK() {
14 try {
15 val policy = HSPolicy().apply {
16 automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorType.INTERCEPT_WITH_DELAYED_RESPONSE // or INTERCEPT_AND_RETRY_REQUEST
17 automaticInterceptorPolicy.setInterceptedDomains(setOf("example.com"), "<APP_ID>")
18 }
19
20 HumanSecurity.start(this, "<APP_ID>", policy)
21 } catch (exception: Exception) {
22 println("Exception: ${exception.message}")
23 }
24 }
25}

Java:

1import android.app.Application;
2import android.util.Log;
3import java.util.HashSet;
4import com.humansecurity.mobile_sdk.HumanSecurity;
5import com.humansecurity.mobile_sdk.main.policy.HSPolicy;
6import com.humansecurity.mobile_sdk.main.policy.HSAutomaticInterceptorType;
7
8public class MainApplication extends Application {
9
10 @Override
11 public void onCreate() {
12 super.onCreate();
13 startHumanSDK();
14 }
15
16 void startHumanSDK() {
17 try {
18 HSPolicy policy = new HSPolicy();
19 policy.getAutomaticInterceptorPolicy().setInterceptorType(HSAutomaticInterceptorType.INTERCEPT_WITH_DELAYED_RESPONSE); // or INTERCEPT_AND_RETRY_REQUEST
20
21 HashSet<String> domains = new HashSet<>();
22 domains.add("example.com");
23 policy.getAutomaticInterceptorPolicy().setInterceptedDomains(domains, "<APP_ID>");
24
25 HumanSecurity.INSTANCE.start(this, "<APP_ID>", policy);
26 } catch (Exception exception) {
27 Log.e("MainApplication", "Exception: " + exception.getMessage());
28 }
29 }
30}

iOS

Swift:

1import UIKit
2import HUMAN
3
4@main
5class AppDelegate: UIResponder, UIApplicationDelegate {
6
7 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
8 startHumanSDK()
9 return true
10 }
11
12 func startHumanSDK() {
13 do {
14 let policy = HSPolicy()
15 policy.automaticInterceptorPolicy.interceptorType = .interceptWithDelayedResponse // or .interceptAndRetryRequest
16 policy.automaticInterceptorPolicy.set(interceptedDomains: ["example.com"], forAppId: "<APP_ID>")
17 HSAutomaticInterceptorPolicy.urlSessionRequestTimeout = 10 // Set the timeout you would like for your requests.
18
19 try HumanSecurity.start(appId: "<APP_ID>", policy: policy)
20 } catch {
21 print("Error: \(error)")
22 }
23 }
24}

Objective-C:

1@import HUMAN;
2
3@implementation AppDelegate
4
5- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
6 [self startHumanSDK];
7 return YES;
8}
9
10- (void)startHumanSDK {
11 HSPolicy *policy = [[HSPolicy alloc] init];
12 policy.automaticInterceptorPolicy.interceptorType = HSAutomaticInterceptorTypeInterceptWithDelayedResponse; // or HSAutomaticInterceptorTypeInterceptAndRetryRequest
13 [policy.automaticInterceptorPolicy setWithInterceptedDomains:[NSSet setWithObject:@"example.com"] forAppId:@"<APP_ID>"];
14 HSAutomaticInterceptorPolicy.urlSessionRequestTimeout = 10; // Set the timeout you would like for your requests.
15
16 NSError *error = nil;
17 [HumanSecurity startWithAppId:@"<APP_ID>" policy:policy error:&error];
18 if (error != nil) {
19 NSLog(@"Error: %@", error);
20 }
21}
22
23@end

Important: Don’t forget to replace <APP_ID> with your actual AppID.

Explanation of the Code

  1. Initialization: Start the SDK as early as possible on the main thread to ensure all URL requests include the necessary HTTP headers.
  2. Policy Configuration: Create an HSPolicy instance to configure the SDK’s behavior. Set the automaticInterceptorPolicy.interceptorType to INTERCEPT_WITH_DELAYED_RESPONSE or INTERCEPT_AND_RETRY_REQUEST to enable the Automatic Interception feature of the SDK. Also, specify the domains your app will interact with.
  3. Starting the SDK: Call the HumanSecurity.start(appId:policy:) function with the application instance (Android only), your AppID, and the configured policy.

Notes:

  • iOS: The Automatic Interception uses URLSessionConfiguration.default. If your app uses a custom configuration, set it in the policy using HSAutomaticInterceptorPolicy.urlSessionConfiguration.
  • Multiple AppIDs: If your app communicates with multiple servers having different AppIDs, use the HumanSecurity.start(appIds:policy:) function to pass an array of AppIDs and specify the relevant AppID for each API call.

Bot Defender Integration

How to Add SDK’s HTTP Headers to Your URL Requests and Handle Blocked Requests

  • Automatic Header Addition: The SDK adds its HTTP headers to your URL requests automatically. It is essential that these HTTP headers are included in every URL request.
  • No Caching of Headers: Do not cache these HTTP headers as they contain a token with an expiration date. The SDK manages this token to ensure it is always up-to-date.
  • Automatic Handling of Blocked Requests: The SDK handles blocked requests and presents a challenge to the user automatically.
  • Custom Error Responses: The SDK provides a custom error response directly to your request handler after the challenge is solved or canceled.
  • Disable Request Timeout:
    • iOS: Set the request timeout to 0 or configure HSAutomaticInterceptorPolicy.urlSessionRequestTimeout to your desired timeout.
    • Android: Set the call/request timeout to 0 (which is also the default value) and configure connectTimeout and read/write timeout as needed.

Example Implementation

Android

In this example, we assume your app uses OkHttp or Ktor. We recommend creating a custom Interceptor for this task. However, you may use any HTTP client of your choice and implement the same logic.

Kotlin (OkHttp):

1import com.humansecurity.mobile_sdk.HumanSecurity
2import com.humansecurity.mobile_sdk.main.HSBotDefenderErrorType
3import okhttp3.OkHttpClient
4import okhttp3.Request
5import java.util.concurrent.TimeUnit
6
7class MyHttpClient {
8
9 private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
10 .callTimeout(0, TimeUnit.SECONDS)
11 .addInterceptor(HSInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
12 .build()
13
14 fun sendRequest(url: String) {
15 try {
16 val request: Request = Request.Builder().url(url).build()
17 okHttpClient.newCall(request).execute().use { response ->
18 if (!response.isSuccessful) {
19 response.body?.string()?.let { responseBody ->
20 when (HumanSecurity.BD.errorType(responseBody)) {
21 HSBotDefenderErrorType.CHALLENGE_WAS_SOLVED -> {
22 println("Challenge was solved")
23 }
24 HSBotDefenderErrorType.CHALLENGE_WAS_CANCELLED -> {
25 println("Challenge was cancelled")
26 }
27 else -> {
28 println("Unknown error")
29 }
30 }
31 }
32 }
33 }
34 } catch (exception: Exception) {
35 println("Request failed. Exception: $exception")
36 }
37 }
38}

Kotlin (Ktor):

1import com.humansecurity.mobile_sdk.HumanSecurity
2import com.humansecurity.mobile_sdk.main.HSBotDefenderErrorType
3import com.humansecurity.mobile_sdk.main.HSInterceptor
4import io.ktor.client.*
5import io.ktor.client.call.body
6import io.ktor.client.engine.okhttp.*
7import io.ktor.client.plugins.HttpTimeout
8import io.ktor.client.request.*
9import io.ktor.client.statement.*
10
11class MyHttpClient {
12
13 private val httpClient: HttpClient = HttpClient(OkHttp) {
14 install(HttpTimeout) {
15 requestTimeoutMillis = HttpTimeout.INFINITE_TIMEOUT_MS
16 }
17 engine {
18 addInterceptor(HSInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
19 }
20 }
21
22 suspend fun sendRequest(url: String) {
23 try {
24 val response: HttpResponse = httpClient.request(url) {}
25 val responseBody = response.body<String>()
26 when (HumanSecurity.BD.errorType(responseBody)) {
27 HSBotDefenderErrorType.CHALLENGE_WAS_SOLVED -> {
28 println("Challenge was solved")
29 }
30 HSBotDefenderErrorType.CHALLENGE_WAS_CANCELLED -> {
31 println("Challenge was cancelled")
32 }
33 else -> {
34 println("Unknown error")
35 }
36 }
37 } catch (exception: Exception) {
38 println("Request failed. Exception: $exception")
39 }
40 }
41}

Java:

1import com.humansecurity.mobile_sdk.HumanSecurity;
2import com.humansecurity.mobile_sdk.main.HSInterceptor;
3import android.util.Log;
4import okhttp3.OkHttpClient;
5import okhttp3.Request;
6import okhttp3.Response;
7import okhttp3.ResponseBody;
8import java.util.concurrent.TimeUnit;
9
10public class MyHttpClient {
11
12 private final OkHttpClient httpClient = new OkHttpClient.Builder()
13 .callTimeout(0, TimeUnit.SECONDS)
14 .addInterceptor(new HSInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
15 .build();
16
17 void sendRequest(String url) {
18 Runnable r = () -> {
19 try {
20 Request request = new Request.Builder().url(url).build();
21 Response response = httpClient.newCall(request).execute();
22 ResponseBody responseBody = response.body();
23 String responseString = null;
24 if (responseBody != null) {
25 responseString = responseBody.string();
26 response.close();
27 }
28 if (!response.isSuccessful() && responseString != null) {
29 switch (HumanSecurity.INSTANCE.getBD().errorType(responseString)) {
30 case CHALLENGE_WAS_SOLVED:
31 Log.i("MyHttpClient", "Challenge was solved");
32 break;
33 case CHALLENGE_WAS_CANCELLED:
34 Log.i("MyHttpClient", "Challenge was cancelled");
35 break;
36 default:
37 Log.i("MyHttpClient", "Unknown error");
38 break;
39 }
40 }
41 } catch (Exception exception) {
42 Log.i("MyHttpClient", "Request failed. Exception: " + exception);
43 }
44 };
45 new Thread(r).start();
46 }
47}

iOS

Using URLSession:

Swift:

1import HUMAN
2
3class MyHttpClient {
4
5 func sendUrlRequest(url: URL) {
6 var request = URLRequest(url: url)
7 request.timeoutInterval = 0 // Disable timeout
8
9 // Configure your request...
10
11 let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
12 if let error {
13 let errorType = HumanSecurity.BD.errorType(error: error)
14 switch errorType {
15 case .challengeWasSolved:
16 print("Challenge was solved")
17 case .challengeWasCancelled:
18 print("Challenge was cancelled")
19 default:
20 print("Unknown error")
21 }
22 }
23 }
24 dataTask.resume()
25 }
26}

Objective-C:

1@import HUMAN;
2
3@implementation MyHttpClient
4
5- (void)sendUrlRequest:(NSURL *)url {
6 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
7 request.timeoutInterval = 0; // Disable timeout
8
9 // Configure your request...
10
11 NSURLSessionDataTask *dataTask = [NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
12 if (error != nil) {
13 HSBotDefenderErrorType errorType = [HumanSecurity.BD errorTypeWithError:error];
14 switch (errorType) {
15 case HSBotDefenderErrorTypeChallengeWasSolved:
16 NSLog(@"Challenge was solved");
17 break;
18 case HSBotDefenderErrorTypeChallengeWasCancelled:
19 NSLog(@"Challenge was cancelled");
20 break;
21 default:
22 NSLog(@"Unknown error");
23 break;
24 }
25 }
26 }];
27 [dataTask resume];
28}
29
30@end

Using Alamofire:

Swift:

1import Alamofire
2import HUMAN
3
4class MyHttpClient {
5
6 func sendUrlRequest(url: URL) {
7 AF.request(url) { $0.timeoutInterval = 0 } // Disable timeout
8 .response { response in
9 if let error = response.error?.underlyingError {
10 let errorType = HumanSecurity.BD.errorType(error: error)
11 switch errorType {
12 case .challengeWasSolved:
13 print("Challenge was solved")
14 case .challengeWasCancelled:
15 print("Challenge was cancelled")
16 default:
17 print("Unknown error")
18 break
19 }
20 }
21 }
22 }
23}

Explanation of the Code

  1. Disable Request Timeout:
    • iOS: Set request.timeoutInterval to 0 or configure HSAutomaticInterceptorPolicy.urlSessionRequestTimeout to your desired timeout.
    • Android: Set the call/request timeout to 0 (default value) and configure connectTimeout and read/write timeout as needed.
  2. Adding HTTP Headers:
    • The SDK automatically adds its HTTP headers to your URL requests via the HSInterceptor. Ensure that this interceptor is the last in the interceptor chain.
  3. Sending the Request:
    • Execute the URL request using your configured HTTP client.
  4. Handling the Response:
    • The SDK provides a custom error response after the challenge is solved or canceled. Check the error type to determine the challenge result (CHALLENGE_WAS_SOLVED or CHALLENGE_WAS_CANCELLED).
    • Note: When HSAutomaticInterceptorType is set to INTERCEPT_AND_RETRY_REQUEST, the SDK will resend the blocked request after the challenge is solved. However, the second request could still be blocked, and the SDK won’t resend it again.

Important: Handle the challenge result appropriately, considering scenarios where the challenge is canceled or the retry attempt fails.

What to Do When a Request Is Blocked

  • Handle as a Failure:
    • Treat blocked requests as failures. 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.
  • Use Handler Callback for Analytics:
    • Utilize the handler callback to log analytics, create logs, etc.
  • Optional Request Retry:
    • You may use the handler callback to retry the original request when appropriate. Consider the following:
      1. Callback Scope: The callback is called outside the original request’s scope. Ensure your app handles this correctly.
      2. Challenge Cancellation: If the challenge is canceled by the user, do not retry the request to avoid it being blocked again.
      3. Retry Block Possibility: The retry attempt may also be blocked. Do not assume it will succeed.

Understanding the Block Response

  1. Enforcer Decision:

    • When HUMAN’s Enforcer decides to block a request, it returns a JSON string in the response body with an HTTP status code of 403. Example response:
    1{
    2 "vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
    3 "appId": "PXj9y4Q8Em",
    4 "action": "captcha",
    5 "collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
    6}

    Note: This JSON contains metadata for the SDK.

  2. Passing Response to SDK:

    • 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.

Setting Custom Parameters for Bot Defender (Optional)

You can configure HUMAN’s backend with additional parameters by setting custom parameters.

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

Key Format: Use keys in the format custom_param[x], where [x] is a number between 1-10.

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

Example Implementation

Android

Kotlin:

1import com.humansecurity.mobile_sdk.HumanSecurity
2
3fun setCustomParametersForBotDefender() {
4 try {
5 val customParameters = HashMap<String, String>().apply {
6 put("custom_param1", "hello")
7 put("custom_param2", "world")
8 }
9 HumanSecurity.BD.setCustomParameters(customParameters, "<APP_ID>")
10 } catch (exception: Exception) {
11 println("Exception: ${exception.message}")
12 }
13}

Java:

1import com.humansecurity.mobile_sdk.HumanSecurity;
2import java.util.HashMap;
3import android.util.Log;
4
5void setCustomParametersForBotDefender() {
6 try {
7 HashMap<String, String> customParameters = new HashMap<>();
8 customParameters.put("custom_param1", "hello");
9 customParameters.put("custom_param2", "world");
10 HumanSecurity.INSTANCE.getBD().setCustomParameters(customParameters, "<APP_ID>");
11 } catch(Exception exception) {
12 Log.e("MainApplication", "Exception: " + exception.getMessage());
13 }
14}
iOS

Swift:

1import HUMAN
2
3func setCustomParametersForBotDefender() {
4 do {
5 let customParameters: [String: String] = [
6 "custom_param1": "hello",
7 "custom_param2": "world"
8 ]
9 try HumanSecurity.BD.setCustomParameters(parameters: customParameters, forAppId: "<APP_ID>")
10 } catch {
11 print("Error: \(error)")
12 }
13}

Objective-C:

1@import HUMAN;
2
3- (void)setCustomParametersForBotDefender {
4 NSMutableDictionary<NSString *, NSString *> *customParameters = [[NSMutableDictionary alloc] init];
5 customParameters[@"custom_param1"] = @"hello";
6 customParameters[@"custom_param2"] = @"world";
7
8 NSError *error = nil;
9 [HumanSecurity.BD setCustomParametersWithParameters:customParameters forAppId:@"<APP_ID>" error:&error];
10 if (error != nil) {
11 NSLog(@"Error: %@", error);
12 }
13}

Account Defender Integration

How to Enable Account Defender in Your App

To enable Account Defender, set the UserID of the currently logged-in user in the SDK.

Example Implementation

Android

Kotlin:

1import com.humansecurity.mobile_sdk.HumanSecurity
2
3fun onUserLoggedIn(userID: String) {
4 try {
5 HumanSecurity.AD.setUserId(userID, "<APP_ID>")
6 } catch (exception: Exception) {
7 println("Exception: ${exception.message}")
8 }
9}

Java:

1import com.humansecurity.mobile_sdk.HumanSecurity;
2import android.util.Log;
3
4void onUserLoggedIn(String userID) {
5 try {
6 HumanSecurity.INSTANCE.getAD().setUserId(userID, "<APP_ID>");
7 } catch(Exception exception) {
8 Log.e("MainApplication", "Exception: " + exception.getMessage());
9 }
10}
iOS

Swift:

1import HUMAN
2
3func onUserLoggedIn(userID: String) {
4 do {
5 try HumanSecurity.AD.setUserId(userId: userID, forAppId: "<APP_ID>")
6 } catch {
7 print("Error: \(error)")
8 }
9}

Objective-C:

1@import HUMAN;
2
3- (void)onUserLoggedIn:(NSString *)userID {
4 NSError *error = nil;
5 [HumanSecurity.AD setUserIdWithUserId:userID forAppId:@"<APP_ID>" error:&error];
6 if (error != nil) {
7 NSLog(@"Error: %@", error);
8 }
9}

How to Notify HUMAN’s Backend on Outgoing URL Requests from the App

To enable Account Defender to protect the user’s account, your app must provide the SDK with outgoing URL requests.

Note: While the SDK’s interceptor is enabled, the SDK automatically collects your outgoing URL requests. No manual API calls are required.

Android

In this example, we assume your app uses OkHttp or Ktor. We recommend creating a custom Interceptor for this task. However, you may use any HTTP client of your choice and implement the same logic.

Kotlin:

1import com.humansecurity.mobile_sdk.HumanSecurity
2import okhttp3.Interceptor
3import okhttp3.Response
4
5class AccountDefenderInterceptor : Interceptor {
6
7 override fun intercept(chain: Interceptor.Chain): Response {
8 val request = chain.request()
9 try {
10 HumanSecurity.AD.registerOutgoingUrlRequest(request.url.toString(), "<APP_ID>")
11 } catch (exception: Exception) {
12 println("Exception: ${exception.message}")
13 }
14 return chain.proceed(request)
15 }
16}

Kotlin (OkHttp):

1import okhttp3.OkHttpClient
2import okhttp3.Request
3
4class MyHttpClient {
5
6 private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
7 .addInterceptor(AccountDefenderInterceptor())
8 .build()
9
10 fun sendRequest(url: String) {
11 try {
12 val request: Request = Request.Builder().url(url).build()
13 okHttpClient.newCall(request).execute().use { response ->
14 // Handle the response...
15 }
16 } catch (exception: Exception) {
17 println("Request failed. Exception: $exception")
18 }
19 }
20}

Kotlin (Ktor):

1import io.ktor.client.*
2import io.ktor.client.engine.okhttp.*
3import io.ktor.client.request.*
4import io.ktor.client.statement.*
5
6class MyHttpClient {
7
8 private val httpClient: HttpClient = HttpClient(OkHttp) {
9 engine {
10 addInterceptor(AccountDefenderInterceptor())
11 }
12 }
13
14 suspend fun sendRequest(url: String) {
15 try {
16 val response: HttpResponse = httpClient.request(url) {}
17 // Handle the response...
18 } catch (exception: Exception) {
19 println("Request failed. Exception: $exception")
20 }
21 }
22}

Java:

1import com.humansecurity.mobile_sdk.HumanSecurity;
2import android.util.Log;
3import java.io.IOException;
4import okhttp3.Interceptor;
5import okhttp3.Request;
6import okhttp3.Response;
7
8public class AccountDefenderInterceptor implements Interceptor {
9
10 @Override
11 public Response intercept(Chain chain) throws IOException {
12 Request request = chain.request();
13 try {
14 HumanSecurity.INSTANCE.getAD().registerOutgoingUrlRequest(request.url().toString(), "<APP_ID>");
15 } catch (Exception exception) {
16 Log.i("AccountDefenderInterceptor", "Exception: " + exception.getMessage());
17 }
18 return chain.proceed(request);
19 }
20}
1import android.util.Log;
2import okhttp3.OkHttpClient;
3import okhttp3.Request;
4import okhttp3.Response;
5
6public class MyHttpClient {
7
8 private final OkHttpClient httpClient = new OkHttpClient.Builder()
9 .addInterceptor(new AccountDefenderInterceptor())
10 .build();
11
12 void sendRequest(String url) {
13 Runnable r = () -> {
14 try {
15 Request request = new Request.Builder().url(url).build();
16 Response response = httpClient.newCall(request).execute();
17 // Handle the response...
18 } catch (Exception exception) {
19 Log.i("MyHttpClient", "Request failed. Exception: " + exception);
20 }
21 };
22 new Thread(r).start();
23 }
24}

iOS

Swift:

1import HUMAN
2
3class MyHttpClient {
4
5 func sendUrlRequest(url: URL) {
6 do {
7 try HumanSecurity.AD.registerOutgoingUrlRequest(url: url.absoluteString, forAppId: "<APP_ID>")
8 } catch {
9 print("Error: \(error)")
10 }
11
12 // Send the request...
13 }
14}

Objective-C:

1@import HUMAN;
2
3@implementation MyHttpClient
4
5- (void)sendUrlRequest:(NSURL *)url {
6 NSError *error = nil;
7 [HumanSecurity.AD registerOutgoingUrlRequestWithUrl:url.absoluteString forAppId:@"<APP_ID>" error:&error];
8 if (error != nil) {
9 NSLog(@"Error: %@", error);
10 }
11
12 // Send the request...
13}
14
15@end

Setting Additional Data for Account Defender (Optional)

You can configure HUMAN’s backend with additional parameters by setting additional data.

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

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

Example Implementation

Android

Kotlin:

1import com.humansecurity.mobile_sdk.HumanSecurity
2
3fun setAdditionalDataForAccountDefender() {
4 try {
5 val additionalData = HashMap<String, String>().apply {
6 put("my_key1", "hello")
7 put("my_key2", "world")
8 }
9 HumanSecurity.AD.setAdditionalData(additionalData, "<APP_ID>")
10 } catch (exception: Exception) {
11 println("Exception: ${exception.message}")
12 }
13}

Java:

1import com.humansecurity.mobile_sdk.HumanSecurity;
2import java.util.HashMap;
3import android.util.Log;
4
5void setAdditionalDataForAccountDefender() {
6 try {
7 HashMap<String, String> additionalData = new HashMap<>();
8 additionalData.put("my_key1", "hello");
9 additionalData.put("my_key2", "world");
10 HumanSecurity.INSTANCE.getAD().setAdditionalData(additionalData, "<APP_ID>");
11 } catch(Exception exception) {
12 Log.e("MainApplication", "Exception: " + exception.getMessage());
13 }
14}
iOS

Swift:

1import HUMAN
2
3func setAdditionalDataForAccountDefender() {
4 do {
5 let additionalData: [String: String] = [
6 "my_key1": "hello",
7 "my_key2": "world"
8 ]
9 try HumanSecurity.AD.setAdditionalData(parameters: additionalData, forAppId: "<APP_ID>")
10 } catch {
11 print("Error: \(error)")
12 }
13}

Objective-C:

1@import HUMAN;
2
3- (void)setAdditionalDataForAccountDefender {
4 NSMutableDictionary<NSString *, NSString *> *additionalData = [[NSMutableDictionary alloc] init];
5 additionalData[@"my_key1"] = @"hello";
6 additionalData[@"my_key2"] = @"world";
7
8 NSError *error = nil;
9 [HumanSecurity.AD setAdditionalDataWithParameters:additionalData forAppId:@"<APP_ID>" error:&error];
10 if (error != nil) {
11 NSLog(@"Error: %@", error);
12 }
13}