Native - Basic Implementation

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

  • Minimal Integration Points: Few points of integration.
  • Handling Blocked Requests: Manage blocked requests effectively.
  • Challenge Notifications: Get notified when a challenge is solved or canceled.
    • Benefits: Great for analytics, logs, etc.
    • Caution: Not recommended to use as a trigger for resending URL requests.
  • No URL Request Interception: The SDK does not intercept your URL requests.

Note:

  • 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

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

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.NONE
17 }
18
19 HumanSecurity.start(this, "<APP_ID>", policy)
20 } catch (exception: Exception) {
21 println("Exception: ${exception.message}")
22 }
23 }
24}

Java:

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

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 = .none
16
17 try HumanSecurity.start(appId: "<APP_ID>", policy: policy)
18 } catch {
19 print("Error: \(error)")
20 }
21 }
22}

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 = HSAutomaticInterceptorTypeNone;
13
14 NSError *error = nil;
15 [HumanSecurity startWithAppId:@"<APP_ID>" policy:policy error:&error];
16 if (error != nil) {
17 NSLog(@"Error: %@", error);
18 }
19}
20
21@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 HSAutomaticInterceptorType.NONE to disable automatic interception of URL requests.
  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 provides HTTP headers that should be added to your app’s URL requests. 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.

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:

1import com.humansecurity.mobile_sdk.HumanSecurity
2import okhttp3.Interceptor
3import okhttp3.Response
4import okhttp3.ResponseBody.Companion.toResponseBody
5
6class BotDefenderInterceptor : Interceptor {
7
8 override fun intercept(chain: Interceptor.Chain): Response {
9 val newRequest = chain.request().newBuilder()
10 val humanHttpHeaders = HumanSecurity.BD.headersForURLRequest("<APP_ID>")
11 for ((key, value) in humanHttpHeaders) {
12 newRequest.header(key, value)
13 }
14 val response = chain.proceed(newRequest.build())
15 if (!response.isSuccessful) {
16 response.body?.string()?.let { responseString ->
17 val isHandled = HumanSecurity.BD.handleResponse(responseString) { result ->
18 println("Challenge result = $result")
19 }
20 if (isHandled) {
21 println("Blocked response was handled by the SDK")
22 return response.newBuilder()
23 .body(HumanSecurity.BD.errorBody(HSBotDefenderErrorType.REQUEST_WAS_BLOCKED).toResponseBody())
24 .build()
25 }
26 }
27 }
28 return response
29 }
30}

Kotlin (OkHttp):

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

Kotlin (Ktor):

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

Java:

1import com.humansecurity.mobile_sdk.HumanSecurity;
2import com.humansecurity.mobile_sdk.main.HSBotDefenderErrorType;
3import java.util.HashMap;
4import android.util.Log;
5import java.io.IOException;
6import okhttp3.Interceptor;
7import okhttp3.Request;
8import okhttp3.Response;
9import okhttp3.ResponseBody;
10import okhttp3.MediaType;
11
12public class BotDefenderInterceptor implements Interceptor {
13
14 @Override
15 public Response intercept(Chain chain) throws IOException {
16 Request.Builder newRequest = chain.request().newBuilder();
17 HashMap<String, String> humanHttpHeaders = HumanSecurity.INSTANCE.getBD().headersForURLRequest("<APP_ID>");
18 for (HashMap.Entry<String, String> entry : humanHttpHeaders.entrySet()) {
19 String key = entry.getKey();
20 String value = entry.getValue();
21 newRequest.header(key, value);
22 }
23 Response response = chain.proceed(newRequest.build());
24 if (!response.isSuccessful()) {
25 ResponseBody responseBody = response.body();
26 if (responseBody != null) {
27 String responseString = responseBody.string();
28 boolean didHandleResponse = HumanSecurity.INSTANCE.getBD().handleResponse(responseString, result -> {
29 Log.i("BotDefenderInterceptor", "Challenge result = " + result);
30 return null;
31 });
32 if (didHandleResponse) {
33 Log.i("BotDefenderInterceptor", "Blocked response was handled by the SDK");
34 return response.newBuilder()
35 .body(ResponseBody.create(HumanSecurity.INSTANCE.getBD().errorBody(HSBotDefenderErrorType.REQUEST_WAS_BLOCKED), MediaType.parse("application/json")))
36 .build();
37 }
38 }
39 }
40 return response;
41 }
42}
1import com.humansecurity.mobile_sdk.HumanSecurity;
2import android.util.Log;
3import okhttp3.OkHttpClient;
4import okhttp3.Request;
5import okhttp3.Response;
6import okhttp3.ResponseBody;
7
8public class MyHttpClient {
9
10 private final OkHttpClient httpClient = new OkHttpClient.Builder()
11 .addInterceptor(new BotDefenderInterceptor()) // SHOULD BE THE LAST INTERCEPTOR
12 .build();
13
14 void sendRequest(String url) {
15 Runnable r = () -> {
16 try {
17 Request request = new Request.Builder().url(url).build();
18 Response response = httpClient.newCall(request).execute();
19 ResponseBody responseBody = response.body();
20 String responseString = null;
21 if (responseBody != null) {
22 responseString = responseBody.string();
23 response.close();
24 }
25 if (!response.isSuccessful() && responseString != null) {
26 switch (HumanSecurity.INSTANCE.getBD().errorType(responseString)) {
27 case REQUEST_WAS_BLOCKED:
28 Log.i("MyHttpClient", "Request was blocked");
29 break;
30 default:
31 Log.i("MyHttpClient", "Unknown error");
32 break;
33 }
34 }
35 } catch (Exception exception) {
36 Log.i("MyHttpClient", "Request failed. Exception: " + exception);
37 }
38 };
39 new Thread(r).start();
40 }
41}

iOS

Using URLSession:

Swift:

1import HUMAN
2
3class MyHttpClient {
4
5 func sendUrlRequest(url: URL) {
6 var request = URLRequest(url: url)
7 let myHttpHeaders = [String: String]()
8
9 // Configure your request and HTTP headers...
10
11 let humanHttpHeaders = HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>")
12 request.allHTTPHeaderFields = myHttpHeaders.merging(humanHttpHeaders) { $1 }
13
14 let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
15 if let data = data, let response = response as? HTTPURLResponse {
16 let isHandled = HumanSecurity.BD.handleResponse(response: response, data: data) { result in
17 print("Challenge result = \(result)")
18 }
19 if isHandled {
20 print("Blocked response was handled by the SDK")
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 NSMutableDictionary<NSString *, NSString *> *myHttpHeaders = [[NSMutableDictionary alloc] init];
8
9 // Configure your request and HTTP headers...
10
11 NSDictionary<NSString *, NSString *> *humanHttpHeaders = [HumanSecurity.BD headersForURLRequestForAppId:@"<APP_ID>"];
12 NSMutableDictionary<NSString *, NSString *> *allHTTPHeaderFields = [[NSMutableDictionary alloc] init];
13 [allHTTPHeaderFields addEntriesFromDictionary:myHttpHeaders];
14 [allHTTPHeaderFields addEntriesFromDictionary:humanHttpHeaders];
15 request.allHTTPHeaderFields = allHTTPHeaderFields;
16
17 NSURLSessionDataTask *dataTask = [NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
18 BOOL isHandled = [HumanSecurity.BD handleResponseWithResponse:response data:data callback:^(enum HSBotDefenderChallengeResult result) {
19 NSLog(@"Challenge result = %ld", (long)result);
20 }];
21 if (isHandled) {
22 NSLog(@"Blocked response was handled by the SDK");
23 }
24 }];
25 [dataTask resume];
26}
27
28@end

Using Alamofire:

Swift:

1import Alamofire
2import HUMAN
3
4class MyHttpClient {
5
6 func sendUrlRequest(url: URL) {
7 var myHttpHeaders = [String: String]()
8
9 // Configure your HTTP headers...
10
11 let humanHttpHeaders = HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>")
12 let allHTTPHeaderFields = myHttpHeaders.merging(humanHttpHeaders) { $1 }
13
14 AF.request(url, headers: HTTPHeaders(allHTTPHeaderFields)).response { response in
15 if let data = response.data, let httpResponse = response.response {
16 let isHandled = HumanSecurity.BD.handleResponse(response: httpResponse, data: data) { result in
17 print("Challenge result = \(result)")
18 }
19 if isHandled {
20 print("Blocked response was handled by the SDK")
21 }
22 }
23 }
24 }
25}

Explanation of the Code

  1. Adding HTTP Headers: Retrieve the SDK’s HTTP headers using HumanSecurity.BD.headersForURLRequest("<APP_ID>") and add them to your URL requests.
  2. Sending the Request: Execute the URL request using your configured HTTP client.
  3. Handling the Response: Use the SDK to determine if the received error indicates a “blocked request.” If so, the SDK presents a challenge to the user.

Note: While your request handler is called, the SDK presents a challenge to the user.

What to Do When a Request Is Blocked

  • Handle as a Failure: Treat blocked requests as failures. Ensure that your app’s UI reflects that the action can be retried after the challenge is solved or canceled by the user. If the request was triggered by a user’s action, inform the user that they may 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.

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 Request 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}