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.
- Benefits:
- 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
’sonCreate
method. - iOS: Initialize in the
AppDelegate
’sdidFinishLaunchingWithOptions
method.
- Android: Initialize in the
- 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 interceptwww.example.com
andapi.example.com
).
Example Implementation
Android
Kotlin:
Java:
iOS
Swift:
Objective-C:
Important: Don’t forget to replace <APP_ID>
with your actual AppID.
Explanation of the Code
- Initialization: Start the SDK as early as possible on the main thread to ensure all URL requests include the necessary HTTP headers.
- Policy Configuration: Create an
HSPolicy
instance to configure the SDK’s behavior. Set theautomaticInterceptorPolicy.interceptorType
toINTERCEPT_WITH_DELAYED_RESPONSE
orINTERCEPT_AND_RETRY_REQUEST
to enable the Automatic Interception feature of the SDK. Also, specify the domains your app will interact with. - 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 usingHSAutomaticInterceptorPolicy.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 configureHSAutomaticInterceptorPolicy.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.
- iOS: Set the request timeout to
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):
Kotlin (Ktor):
Java:
iOS
Using URLSession
:
Swift:
Objective-C:
Using Alamofire:
Swift:
Explanation of the Code
- Disable Request Timeout:
- iOS: Set
request.timeoutInterval
to0
or configureHSAutomaticInterceptorPolicy.urlSessionRequestTimeout
to your desired timeout. - Android: Set the call/request timeout to
0
(default value) and configureconnectTimeout
andread/write timeout
as needed.
- iOS: Set
- 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.
- The SDK automatically adds its HTTP headers to your URL requests via the
- Sending the Request:
- Execute the URL request using your configured HTTP client.
- 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
orCHALLENGE_WAS_CANCELLED
). - Note: When
HSAutomaticInterceptorType
is set toINTERCEPT_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.
- The SDK provides a custom error response after the challenge is solved or canceled. Check the error type to determine the challenge result (
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:
- 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.
- You may use the handler callback to retry the original request when appropriate. Consider the following:
Understanding the Block Response
-
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:
Note: This JSON contains metadata for the SDK.
- When HUMAN’s Enforcer decides to block a request, it returns a JSON string in the response body with an HTTP status code of
-
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.
- Your app should pass the entire JSON response to the SDK via the
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:
Java:
iOS
Swift:
Objective-C:
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:
Java:
iOS
Swift:
Objective-C:
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:
Kotlin (OkHttp):
Kotlin (Ktor):
Java:
iOS
Swift:
Objective-C:
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:
Java:
iOS
Swift:
Objective-C: