Skip to main content

Kotlin SDK

dev.k9o:gate is the mobile Gate (IAK) SDK for Kotlin. It exposes three methods — signIn, refreshToken, and signOut — for end-users of your application. It is an auth-only SDK: there is no data-plane from() surface here. Platform operations (data, migrations, functions, policies) are the domain of the eight full-platform server SDKs. For client-side BYOK/HYOK key operations, the dev.k9o:kibo sibling package pairs with this SDK.

Minimum targets: Android API 24+ (full feature set) and Kotlin Multiplatform (JVM, Native, JS targets). Every Gate method is a suspend function — structured concurrency and coroutines throughout. Errors surface as thrown GateError exceptions. Access and refresh tokens persist to EncryptedSharedPreferences backed by the Android Keystore on Android; on KMP targets the token store is configurable.


Installation​

Gradle (Kotlin DSL)​

// build.gradle.kts
dependencies {
implementation("dev.k9o:gate:1.5.0")
}

Gradle (Groovy DSL)​

// build.gradle
dependencies {
implementation 'dev.k9o:gate:1.5.0'
}

The import root is dev.k9o.gate.


Setup​

Construct the Gate client once — typically in a ViewModel, Hilt/Koin module, or Application subclass. The client takes four parameters:

  • orgBaseUrl — your organisation's regional API address, for example https://acme.api-de01.k9o.io. Use the regional address, not the region-free one: the region-free address only answers with a redirect, which the mobile clients do not follow. No path segment; a path-bearing URL throws K9O_INVALID_BASE_URL at construction time.
  • projectSlug — the project slug that identifies which Gate configuration to authenticate against.
  • tokenStore — KeystoreTokenStore(applicationContext) on Android, which wraps EncryptedSharedPreferences backed by the Android Keystore. Pass a custom TokenStore implementation to override (useful in tests or on KMP non-Android targets).
  • httpClient — an OkHttpClient instance. Supply your own to share connection pools, attach interceptors, or configure timeouts. OkHttp's default read timeout is 10 seconds, which is too short for analytics queries and model calls (a model call can take about 30 seconds); raise it with OkHttpClient.Builder().readTimeout(60, TimeUnit.SECONDS).

There is no API key. The app is unauthenticated until the end-user calls signIn. Embedding any server-side credential (API key, service token, PAT) in a mobile binary is a security hazard — Gate mobile SDKs are intentionally keyless at construction time.

Kotlin
import dev.k9o.gate.GateClient
import dev.k9o.gate.KeystoreTokenStore

// Construct once — share via DI (Hilt, Koin, or a companion object singleton).
val gate = GateClient(
  orgBaseUrl   = "https://acme.api-de01.k9o.io", // your organisation's regional address
  projectSlug  = "member-portal",
  tokenStore   = KeystoreTokenStore(applicationContext), // EncryptedSharedPreferences-backed
)

Showing example in Kotlin

On Android, KeystoreTokenStore stores tokens in a SharedPreferences file encrypted with a key held in the Android Keystore. The key is bound to the device and never leaves it. On KMP targets without EncryptedSharedPreferences, provide a custom TokenStore backed by the platform's secure credential store.


Authenticating the end-user​

Sign in with email and password​

signIn(email, password) calls the Gate sign-in endpoint and, on success, persists the returned access and refresh token pair to tokenStore. Returns an AuthResult containing an EndUser and a Session.

Kotlin
import dev.k9o.gate.GateClient
import dev.k9o.gate.GateError

// Inside a coroutine or suspend function:
try {
  val result = gate.signIn(
      email    = "[email protected]",
      password = "••••••••"
  )
  // Session is persisted to EncryptedSharedPreferences automatically.
  println("Signed in as: ${result.user.id}")
  println("Access token: ${result.session.accessToken}")
} catch (e: GateError.InvalidCredentials) {
  // Wrong email or password — prompt the user to try again.
  showSnackbar("Incorrect email or password.")
} catch (e: GateError.Network) {
  // No connection.
} catch (e: GateError.Unknown) {
  Log.e("Gate", "HTTP ${e.statusCode}: ${e.body}")
}
Output · bash
Signed in as: eu_FlnW5CipGlAH
Access token: eyJhbGciOiJSUzI1NiIs...

Showing example in Kotlin

Sign out​

signOut() revokes the stored refresh token server-side and clears the persisted tokens from tokenStore. It returns a Boolean (true when a live session was revoked).

Kotlin
try {
  gate.signOut()
  // Tokens cleared from EncryptedSharedPreferences; user must sign in again.
  navigateToSignIn()
} catch (e: GateError) {
  Log.e("Gate", "Sign-out failed: $e")
}

Showing example in Kotlin

Refresh token​

Access tokens live 30 minutes by default; the project's session settings change this. Call refreshToken() to exchange the stored refresh token for a fresh access token. The result is a RefreshResult with accessToken, refreshToken and expiresAt. Each refresh returns a new refresh token and the one you sent stops working; the SDK keeps the new one in the tokenStore. Sending an old refresh token again ends the session. revokeAllSessions ends every session of the signed-in user, this device included. See Session lifetime and sign-out.

Kotlin
try {
  val refreshed = gate.refreshToken()
  println("Refreshed. New access token: ${refreshed.accessToken}, expires ${refreshed.expiresAt}")
} catch (e: GateError.InvalidCredentials) {
  // Refresh token unknown, used or revoked — send the user back to the sign-in screen.
  navigateToSignIn()
} catch (e: GateError.Unauthenticated) {
  // No stored refresh token.
  navigateToSignIn()
}
Output · bash
Refreshed. New access token: eyJhbGciOiJSUzI1NiIs..., expires 2026-10-27T00:20:15.000Z

Showing example in Kotlin


Using the session​

The access token is a signed JWT. Attach it to your own backend calls as a Bearer token in the Authorization header. The SDK exposes the raw JWT string and a structured AccessToken decoder:

Kotlin
// Attach to OkHttp / Retrofit via an Interceptor:
val authInterceptor = Interceptor { chain ->
  val request = chain.request().newBuilder()
      .addHeader("Authorization", "Bearer ${accessToken}")
      .build()
  chain.proceed(request)
}

// Decode claims without a network call:
val claims = AccessToken.decode(accessToken)
println("Subject: ${claims?.subject}")
println("Expires: ${claims?.expiresAt}")
val partnerRole = claims?.customClaim("myapp", "role")   // reads ext.myapp.role
Output · bash
Subject: eu_FlnW5CipGlAH
Expires: 1793096100
Custom claims added by your project's Gate configuration (flat ext.<namespace>.<name> keys):

Showing example in Kotlin

Token lifecycle. The access token TTL defaults to 1 hour (configurable per project in the Console). Call refreshToken() proactively before the access token expires — or handle 401 responses from your API calls by refreshing and retrying once. If refreshToken() itself throws GateError.InvalidCredentials or GateError.Unauthenticated, the refresh token is no longer valid and the user must sign in again.

Coroutine context. All Gate methods are suspend functions. Call them from a CoroutineScope with an appropriate dispatcher — Dispatchers.IO for standalone calls, or from a viewModelScope / lifecycleScope to automatically cancel on lifecycle tear-down.


Error handling​

The SDK throws GateError, a sealed class, on every failure:

Kotlin
import dev.k9o.gate.GateClient
import dev.k9o.gate.GateError

try {
  val result = gate.signIn(email = email, password = password)
  handleSession(result.session)
} catch (e: GateError.InvalidCredentials) {
  showError("Incorrect email or password.")
} catch (e: GateError.Unauthenticated) {
  navigateToSignIn()
} catch (e: GateError.Forbidden) {
  showError("You do not have access.")
} catch (e: GateError.Network) {
  showError("No connection.")
} catch (e: GateError.Decoding) {
  Log.e("Gate", "Unexpected response")
} catch (e: GateError.Unknown) {
  Log.e("Gate", "HTTP ${e.statusCode}: ${e.body}")
}

Showing example in Kotlin

Cases:

CaseWhen it fires
InvalidCredentialsWrong email or password on signIn; unknown or revoked refresh token on refreshToken
UnauthenticatedNo valid session, or no stored refresh token
ForbiddenThe caller lacks permission for the operation
NetworkTransport failure
DecodingThe response could not be decoded
UnknownAny other non-2xx status, with statusCode and body

SSO, social, and passwordless sign-in​

SSO, social providers, and passwordless flows are handled through the Auth API reference and the server-side TypeScript SDK (or other server SDK). The mobile Gate SDK covers credential-based sign-in for end-users; richer provider flows are available server-side.


See also​

  • Auth API reference — Gate IAK full surface: MFA, social / OIDC / SAML, admin recovery.
  • TypeScript SDK — server-side SDK with the full auth surface including SSO and passwordless.
  • Kibo — client-side BYOK/HYOK ZK sibling SDK (dev.k9o:kibo).
  • SDKs — all twelve v2 SDK languages.