> This is a page from the Castle documentation. For an index of the documentation, fetch https://castle.io/llms.txt.

# Mobile SDKs

How to install, configure and use the Castle Mobile SDKs to perform device fingerprinting and monitor user activity.

> 📘 ### Mobile integration requires the Enterprise plan
>
> Castle mobile SDKs are available only to customers on the Enterprise plan.
>
> For detailed installation instructions, open [Getting started → Full integration](https://dashboard.castle.io/getting-started/full-integration) in the Castle Dashboard.

## Introduction

The Castle mobile SDKs add Castle to iOS and Android apps. They provide device fingerprinting, behavioral analysis, and client-side event monitoring.

Like the Browser SDK, the mobile SDKs have two main purposes:

- [Creating request tokens](#creating-request-tokens): generate a unique token. Send it to your server and use it when you call the Castle Risk and Filter APIs.
- [Tracking client-side events](#tracking-client-side-events): send important in-app events from the app to the Castle API.

## Requirements

To integrate Castle with your mobile app, you need:

- [A Castle account](https://dashboard.castle.io/signup/new) with _admin_ access.
- An app that you can run locally.
- **iOS**: version 13 or later.
- **Android**: minSdk 26 or later, compileSdk 36 or later, and a JDK 17 toolchain. Supported ABIs: armeabi-v7a, arm64-v8a, x86, and x86_64.

## Integration

Mobile SDKs provide packages for React Native, Flutter, Swift and Maven.

Find the installation instructions in the Castle Dashboard, under [Getting started → Full integration](https://dashboard.castle.io/getting-started/full-integration).

## Configuration

After you install the SDK, configure it with your Publishable Key. Find the key in [Environment Settings → API Keys](https://dashboard.castle.io/settings/environment/api-keys).

```swift title="Swift"
import CastleSDK

do {
    try Castle.configure(publishableKey: "{Publishable-API-Key}")
} catch {
    print("Castle configure failed: \(error)")
}
```
```objc title="Objective-C"
@import CastleSDK;

NSError *error = nil;
BOOL success = [Castle configureWithPublishableKey:@"{Publishable-API-Key}" error:&error];
if (!success) {
    NSLog(@"Castle configure failed: %@", error);
}
```
```java title="Java"
import io.castle.Castle;
import io.castle.Configuration;
import io.castle.ConfigurationError;

Configuration configuration = new Configuration.Builder()
    .publishableKey("{Publishable-API-Key}")
    .build();
try {
    Castle.configure(this, configuration);
} catch (ConfigurationError e) {
    Log.e("Castle", "configure failed: " + e.getMessage());
}
```
```kotlin title="Kotlin"
import io.castle.Castle
import io.castle.Configuration
import io.castle.ConfigurationError

val configuration = Configuration.Builder()
    .publishableKey("{Publishable-API-Key}")
    .build()
try {
    Castle.configure(this, configuration)
} catch (e: ConfigurationError) {
    Log.e("Castle", "configure failed: ${e.message}")
}
```
```javascript title="React Native"
import Castle from '@castleio/react-native-castle';

try {
  await Castle.configureWithPublishableKey('{Publishable-API-Key}');
} catch (e) {
  console.error('Castle configure failed:', e);
}
```
```dart title="Flutter"
import 'package:castle_flutter/castle.dart';

try {
  await Castle.configure(publishableKey: "{Publishable-API-Key}");
} on PlatformException catch (e) {
  debugPrint("Castle configure failed: ${e.message}");
}
```

Configuring the SDK early in the app lifecycle is recommended to allow more time for sensor data collection before the first token is created. Call `configure` in `Application.onCreate()` on Android, or on the main thread on iOS. iOS also supports awaiting configuration with `Castle.configureAsync`. Request tokens can be created immediately after configuration.

## Creating request tokens

Call `createRequestToken` to generate a request token. The Risk and Filter APIs require this token. Send the request token as a header with **every request** to your API.

Generate a **new token for each request** to your backend. A token is **valid for 120 seconds**.

`createRequestToken` has no options. It creates tokens synchronously. You can call it from a background thread.

```swift title="Swift"
let token = Castle.createRequestToken()
if let token {
    request.setValue(token, forHTTPHeaderField: "X-Castle-Request-Token")
}
```
```objc title="Objective-C"
NSString *token = [Castle createRequestToken];
if (token != nil) {
    [request setValue:token forHTTPHeaderField:@"X-Castle-Request-Token"];
}
```
```java title="Java"
String token = Castle.createRequestToken();
if (token != null) {
    request.header("X-Castle-Request-Token", token);
}
```
```kotlin title="Kotlin"
val token = Castle.createRequestToken()
if (token != null) {
    request.addHeader("X-Castle-Request-Token", token)
}
```
```javascript title="React Native"
const token = await Castle.createRequestToken();
if (token != null) {
  await fetch('https://example.com', {
    headers: { [await Castle.requestTokenHeaderName()]: token },
  });
}
```
```dart title="Flutter"
final token = await Castle.createRequestToken;
if (token != null) {
  request.headers.set("X-Castle-Request-Token", token);
}
```

`createRequestToken` returns `null` if the SDK is not configured or if configuration failed. In a future version, it will always return a token. It will throw an exception if the SDK is not configured.

## Tracking client-side events

`Castle.custom(...)` and `Castle.screen(...)` create events containing a device token and an event or screen name. Custom events can also include properties. These events provide behavioral context for detection and are sent only after a user JWT has been set.

### Step 1. Expose a signed user JWT from your backend

Your backend builds a user payload and signs it as a JWT. Your app gets the JWT and passes it to `Castle.setUserJwt(...)` before it tracks events.

The payload uses the same user fields as the Risk and Filter APIs.

```ruby
def castle_user
  return {
    id: 'ca1242f498', # required
    email: 'mbrown@mailinator.com', # required
    phone: '+1415232183', # required if email is not present
    name: 'Michael Brown',
    registered_at: '2012-12-02T00:30:08.276Z',
    traits: {
      plan: 'premium'
    }
  }
end
```

Sign the payload on your backend with your Castle API Secret. When Castle receives the JWT, it verifies the signature. The client cannot change the content.

Serve the signed token from an authenticated endpoint. Your app calls it for the logged-in user:

```ruby
# Require authorization so that you can access the logged-in user
post '/castle_user_jwt' do
  JWT.encode(castle_user, ENV.fetch('CASTLE_API_SECRET'), 'HS256')
end
```

### Step 2. Setting the user in your app

Pass the user JWT to `Castle.setUserJwt(...)`. The SDK treats the JWT as an opaque string. It stores the value and sends it unchanged with your events.

```swift title="Swift"
Castle.userJwt("{user-JWT}")
```
```objc title="Objective-C"
[Castle setUserJwt:@"{user-JWT}"];
```
```java title="Java"
Castle.setUserJwt("{user-JWT}");
```
```kotlin title="Kotlin"
Castle.setUserJwt("{user-JWT}")
```
```javascript title="React Native"
await Castle.userJwt('{user-JWT}');
```
```dart title="Flutter"
await Castle.userJwt("{user-JWT}");
```

### Step 3. Sending screen views from your app

Call `screen` with the screen name to track navigation, including onboarding steps and sensitive screens such as transactions and user settings. Centralizing the call in a navigation handler avoids adding it to each screen.

```swift title="Swift"
Castle.screen(name: "Onboarding – Verify documents")
```
```objc title="Objective-C"
[Castle screenWithName:@"Onboarding – Verify documents"];
```
```java title="Java"
Castle.screen("Onboarding – Verify documents");
```
```kotlin title="Kotlin"
Castle.screen("Onboarding – Verify documents")
```
```javascript title="React Native"
await Castle.screen('Onboarding – Verify documents');
```
```dart title="Flutter"
await Castle.screen("Onboarding – Verify documents");
```

### Step 4. Sending custom events from your app

Call `custom` for a user action that needs extra information. Pass the action name and any properties that help detection.

```swift title="Swift"
let properties: [String: Any] = [
    "product": "iPhone 13 Pro",
    "price": 1099.99
]
Castle.custom(name: "Added to Cart", properties: properties)
```
```objc title="Objective-C"
NSDictionary *properties = @{
    @"product": @"iPhone 13 Pro",
    @"price": 1099.99
};
[Castle customWithName:@"Added to Cart"
            properties:properties];
```
```java title="Java"
Castle.custom("Added to Cart", Map.of(
   "product", "iPhone 13 Pro",
   "price", 1099.99
));
```
```kotlin title="Kotlin"
Castle.custom("Added to Cart", mapOf(
   "product" to "iPhone 13 Pro",
   "price" to 1099.99
))
```
```javascript title="React Native"
await Castle.customWithProperties('Added to Cart', {
  product: 'iPhone 13 Pro',
  price: 1099.99
});
```
```dart title="Flutter"
await Castle.custom("Added to Cart", {
  "product": "iPhone 13 Pro",
  "price": 1099.99
});
```

Custom properties support basic types, such as `String`, `Int` and `Long`. They do not support `List` or `Map`. The `custom` and `screen` events are fire-and-forget. They do their work asynchronously, to ensure fast execution.

## Additional configuration

Optional settings control logging, event queueing, and automatic tracking.

```swift title="Swift"
let configuration = CastleConfiguration(publishableKey: "{Publishable-API-Key}")
configuration.isDebugLoggingEnabled = false // Default
configuration.flushLimit = 20 // Default
configuration.maxQueueLimit = 1000 // Default
configuration.isScreenTrackingEnabled = false // Default
configuration.isApplicationLifecycleTrackingEnabled = true // Default
configuration.isTouchCollectionEnabled = true // Default, iOS 4.3.0+
configuration.baseURLAllowList = [URL(string: "https://example.com")!]

try Castle.configure(configuration)
```
```objc title="Objective-C"
CastleConfiguration *configuration = [CastleConfiguration configurationWithPublishableKey:@"{Publishable-API-Key}"];
configuration.debugLoggingEnabled = NO; // Default
configuration.flushLimit = 20; // Default
configuration.maxQueueLimit = 1000; // Default
configuration.screenTrackingEnabled = NO; // Default
configuration.enableApplicationLifecycleTracking = YES; // Default
configuration.touchCollectionEnabled = YES; // Default, iOS 4.3.0+
configuration.baseURLAllowList = @[[NSURL URLWithString:@"https://example.com"]];

NSError *error = nil;
BOOL success = [Castle configure:configuration error:&error];
if (!success) {
    NSLog(@"Castle configure failed: %@", error);
}
```
```java title="Java"
Configuration configuration = new Configuration.Builder()
  .publishableKey("{Publishable-API-Key}")
  .debugLoggingEnabled(false) // Default
  .flushLimit(20) // Default
  .maxQueueLimit(1000) // Default       
  .screenTrackingEnabled(false) // Default
  .applicationLifecycleTrackingEnabled(true) // Default
  .baseURLAllowList(java.util.Collections.singletonList("https://example.com/"))
  .build();

try {
  Castle.configure(application, configuration);
} catch (ConfigurationError e) {}
```
```kotlin title="Kotlin"
val configuration = Configuration.Builder()
  .publishableKey("{Publishable-API-Key}")
  .debugLoggingEnabled(false) // Default
  .flushLimit(20) // Default
  .maxQueueLimit(1000) // Default       
  .screenTrackingEnabled(false) // Default
  .applicationLifecycleTrackingEnabled(true) // Default
  .baseURLAllowList(listOf("https://example.com/"))
  .build()

try {
  Castle.configure(application, configuration)
} catch (e: ConfigurationError) {}
```
```javascript title="React Native"
const configuration = await Castle.configure({
  publishableKey: '{Publishable-API-Key}',
  debugLoggingEnabled: false,
  flushLimit: 20, // default: 20
  maxQueueLimit: 1000, // default: 1000
  useCloudflareApp: false,
  apiDomain: 'castle.example.com', // custom API domain, e.g. a proxy
  apiPath: '/v1/', // custom API path
  baseURLAllowList: ['https://api.example.com'], // hosts that receive the request token
  lifeCycleEventsEnabled: true, // track application lifecycle events
  touchCollectionEnabled: true, // iOS only, ignored on Android
});
```
```dart title="Flutter"
await Castle.configure(
  publishableKey: "{Publishable-API-Key}",
  debugLoggingEnabled: false, // Default
  flushLimit: 20, // Default
  maxQueueLimit: 1000, // Default
  baseURLAllowList: ["https://api.example.com"],
  lifeCycleEventsEnabled: true,
  touchCollectionEnabled: true, // iOS only, no effect on Android
);
```

`flushLimit` is the number of queued events that triggers a flush. `maxQueueLimit` is the maximum number of events kept in the queue.

Touch collection collects behavioral touch and swipe data for bot detection. When disabled, detection based on this data is unavailable. Android has no equivalent setting.

Application lifecycle tracking records app lifecycle events, like foreground and background transitions. Automatic screen tracking records views of Activities on Android and UIViewControllers on iOS. On iOS, it uses method swizzling on `UIViewController.viewDidAppear`.

### Queue flushing

The SDK flushes queued events on app lifecycle events or when the number of queued events reaches `flushLimit`. Flushing requires a user JWT.

### Advertising identifiers

The SDK can use the platform advertising identifier as an additional signal for device fingerprinting. This is optional and **not** collected by the SDK. The app must collect it, ensure the permissions and pass it to the SDK.

On Android, the identifier is supplied through `adIdProvider`. Apps targeting Android 13 or later that access the Google advertising ID must declare `com.google.android.gms.permission.AD_ID`. The SDK ignores NULL values.

On iOS, the identifier is supplied through `adSupportBlock` and requires App Tracking Transparency authorization. The app must include `NSUserTrackingUsageDescription` in `Info.plist`.

Empty values or null are ignored by the SDK.

```swift title="Swift"
import AdSupport
import AppTrackingTransparency
import CastleSDK

let configuration = CastleConfiguration(publishableKey: "{Publishable-API-Key}")

configuration.isAdvertisingTrackingEnabled = true // Default
configuration.adSupportBlock = {
    // Request authorization separately, e.g. once the app is active:
    // ATTrackingManager.requestTrackingAuthorization { _ in }
    let status = ATTrackingManager.trackingAuthorizationStatus
    guard status == .authorized else { return "" }
    return ASIdentifierManager.shared().advertisingIdentifier.uuidString
}

try Castle.configure(configuration)
```
```objc title="Objective-C"
@import AdSupport;
@import AppTrackingTransparency;
@import CastleSDK;

CastleConfiguration *configuration = [CastleConfiguration configurationWithPublishableKey:@"{Publishable-API-Key}"];

configuration.enableAdvertisingTracking = YES; // Default
configuration.adSupportBlock = ^NSString * {
    // Request authorization separately, e.g. once the app is active:
    // [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus s) {}];
    ATTrackingManagerAuthorizationStatus status = ATTrackingManager.trackingAuthorizationStatus;
    if (status != ATTrackingManagerAuthorizationStatusAuthorized) {
        return @"";
    }
    return [ASIdentifierManager.sharedManager.advertisingIdentifier UUIDString];
};

NSError *error = nil;
BOOL success = [Castle configure:configuration error:&error];
if (!success) {
    NSLog(@"Castle configure failed: %@", error);
}
```
```java title="Java"
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import io.castle.Configuration;

Configuration configuration = new Configuration.Builder()
        .publishableKey("{Publishable-API-Key}")
        .adIdProvider(() -> {
            try {
                return AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId();
            } catch (Exception ignored) {
                return null;
            }
        })
        .build();
```
```kotlin title="Kotlin"
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import io.castle.Configuration

val configuration = Configuration
    .Builder()
    .publishableKey("{Publishable-API-Key}")
    .adIdProvider {
        try {
            AdvertisingIdClient.getAdvertisingIdInfo(applicationContext).id
        } catch (_: Exception) {
            null
        }
    }
    .build()
```
```javascript title="React Native"
const adId = await getAdvertisingId(); // from ad-ID library
if (adId) await Castle.setAdvertisingIdentifier(adId);
```
```dart title="Flutter"
final adId = await getAdvertisingId(); // from ad-ID library
if (adId != null) await Castle.advertisingIdentifier(adId);
```

## Automatically adding request tokens

Castle can automatically generate a request token and attach it to outgoing requests whose destination matches the `baseURLAllowList`. The token is sent in the `X-Castle-Request-Token` header (`Castle.requestTokenHeaderName`). Requests to destinations outside the allowlist are left unchanged.

On iOS, automatic token attachment requires `isTokenAutoForwardingEnabled` to be enabled and `baseURLAllowList` to be configured. The SDK uses a custom `URLProtocol` to attach tokens to supported requests made through Apple's URL Loading System.

On Android, automatic token attachment requires a configured `baseURLAllowList` and an `OkHttpClient` with `Castle.castleInterceptor()` added. Tokens are added only to matching requests made through that client. Retrofit integrations must use the same configured client.

```swift title="Swift"
let configuration = CastleConfiguration(publishableKey: "{Publishable-API-Key}")
configuration.isTokenAutoForwardingEnabled = true
configuration.baseURLAllowList = [URL(string: "https://example.com")!]
try? Castle.configure(configuration)

let url = URL(string: "https://example.com/v1/task")!
URLSession.shared.dataTask(with: url) { _, _, _ in
}.resume()
```
```objc title="Objective-C"
CastleConfiguration *configuration =
    [CastleConfiguration configurationWithPublishableKey:@"{Publishable-API-Key}"];
configuration.tokenAutoForwardingEnabled = YES;
configuration.baseURLAllowList = @[ [NSURL URLWithString:@"https://example.com"] ];
NSError *error = nil;
[Castle configure:configuration error:&error];

NSURL *url = [NSURL URLWithString:@"https://example.com/v1/task"];
[[[NSURLSession sharedSession] dataTaskWithURL:url
                             completionHandler:^(NSData *_Nullable data,
                                                 NSURLResponse *_Nullable response,
                                                 NSError *_Nullable error) {
                             }] resume];
```
```java title="Java"
Configuration configuration = new Configuration.Builder()
  .publishableKey("{Publishable-API-Key}")
  .baseURLAllowList(java.util.Collections.singletonList("https://example.com/"))
  .build();
Castle.configure(application, configuration);

OkHttpClient client = new OkHttpClient.Builder()
  .addInterceptor(Castle.castleInterceptor())
  .build();
```
```kotlin title="Kotlin"
val configuration = Configuration.Builder()
  .publishableKey("{Publishable-API-Key}")
  .baseURLAllowList(listOf("https://example.com/"))
  .build()
Castle.configure(application, configuration)

val client = OkHttpClient.Builder()
  .addInterceptor(Castle.castleInterceptor())
  .build()
```
