Skip to main content

Swift SDK

K9OGate is the mobile Gate (IAK) SDK for Swift. It covers the end-user authentication surface — 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 K9OKibo sibling package pairs with this SDK via the same SwiftPM repository.

Minimum platform targets: iOS 17+ / macOS 14+ / iPadOS 17+ / tvOS 17+ / watchOS 10+ / visionOS 1+. Swift Concurrency (async/await) throughout. Every call is a throwing async function that throws a K9OGateError on failure. Access and refresh tokens persist to Keychain with biometric protection where the device supports it.


Installation​

Swift Package Manager​

Add the package in Package.swift:

// Package.swift
.package(url: "https://github.com/k9o-dev/sdk-swift.git", from: "1.5.0")

Then add the K9OGate product to your target:

.target(
name: "MyApp",
dependencies: [
.product(name: "K9OGate", package: "sdk-swift"),
]
)

Xcode: File → Add Package Dependencies → https://github.com/k9o-dev/sdk-swift.git → add the K9OGate product to your app target.

CocoaPods​

pod 'K9OGate'

Setup​

Construct the Gate client once — typically in your app-level @main entry point or a dedicated AuthService singleton. The client takes three arguments:

  • orgBaseURL — your organisation's regional API address as a URL value, for example URL(string: "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 — optional. Defaults to the built-in KeychainTokenStore, which persists the access and refresh tokens to the iOS / macOS Keychain with biometric protection where available. Pass a custom conforming type to override (useful in test environments).

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.

Swift
import K9OGate

// Construct once — share as a singleton or inject via your DI container.
let gate = GateClient(
  orgBaseURL: URL(string: "https://acme.api-de01.k9o.io")!,  // your organisation's regional address
  projectSlug: "member-portal"
  // tokenStore defaults to KeychainTokenStore() — omit unless overriding
)

Showing example in Swift

The KeychainTokenStore stores tokens under a per-projectSlug Keychain item group, so multiple Gate projects can coexist on the same device without collision.


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. The returned AuthResult carries the end-user identity and the token pair.

Swift
import K9OGate

do {
  let result = try await gate.signIn(
      email: "[email protected]",
      password: "••••••••"
  )
  // Session is persisted to Keychain automatically.
  print("Signed in as: \(result.user.id)")
  print("Access token: \(result.session.accessToken)")
} catch K9OGateError.invalidCredentials {
  print("Wrong email or password.")
} catch K9OGateError.network(let error) {
  print("Network problem: \(error.localizedDescription)")
} catch {
  print("Sign-in failed: \(error.localizedDescription)")
}
Output · bash
Signed in as: eu_8f3kQ2mZ
Access token: eyJhbGciOiJSUzI1NiIs...

Showing example in Swift

Sign out​

signOut() revokes the stored refresh token server-side and clears the persisted tokens from tokenStore. It returns a Bool (true when a live session was revoked); with no stored token it sends nothing.

Swift
do {
  try await gate.signOut()
  // Tokens cleared from Keychain; user must sign in again.
} catch {
  print("Sign-out failed: \(error.localizedDescription)")
}

Showing example in Swift

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

Swift
do {
  let refreshed = try await gate.refreshToken()
  print("Refreshed. New access token: \(refreshed.accessToken), expires \(refreshed.expiresAt)")
} catch K9OGateError.invalidCredentials {
  navigateToSignIn()   // refresh token unknown, used or revoked
} catch K9OGateError.unauthenticated {
  navigateToSignIn()   // no stored refresh token
}
Output · bash
Refreshed. New access token: eyJhbGciOiJSUzI1NiIs..., expires 2026-10-27T11:15:00Z

Showing example in Swift


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 K9OAccessToken decoder:

Swift
// Attach to URLRequest:
var request = URLRequest(url: myBackendURL)
request.setValue("Bearer \(result.session.accessToken)", forHTTPHeaderField: "Authorization")

// Decode claims without a network call:
if let claims = K9OAccessToken.decode(result.session.accessToken) {
  print("Subject:  \(claims.subject ?? "")")
  print("Expires:  \(String(describing: claims.expiresAt))")
  let partnerRole = claims.customClaim(namespace: "myapp", name: "role")   // reads ext.myapp.role
}
Output · bash
Subject:  eu_8f3kQ2mZ
Expires:  Optional(2026-10-27 10:15:00 +0000)
Custom claims added by your project's Gate configuration (flat ext.<namespace>.<name> keys):

Showing example in Swift

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 fails with K9OGateError.invalidCredentials or K9OGateError.unauthenticated, the refresh token is no longer valid and the user must sign in again.


Error handling​

The SDK throws K9OGateError on every failure. It has six cases:

Swift
import K9OGate

do {
  let result = try await gate.signIn(email: email, password: password)
  handleResult(result)
} catch K9OGateError.invalidCredentials {
  showAlert("Incorrect email or password.")
} catch K9OGateError.unauthenticated {
  navigateToSignIn()
} catch K9OGateError.forbidden {
  showAlert("You do not have access.")
} catch K9OGateError.network(let error) {
  logger.error("Network problem: \(error.localizedDescription)")
} catch K9OGateError.decoding(let error) {
  logger.error("Unexpected response: \(error.localizedDescription)")
} catch K9OGateError.unknown(let statusCode, let body) {
  logger.error("HTTP \(statusCode): \(body ?? "")")
}

Showing example in Swift

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: DNS, TCP, timeout
decodingThe response could not be decoded
unknownAny other non-2xx status, with the status code and body

Social and SSO sign-in​

Social providers (Google, Apple, GitHub), OIDC, and SAML federation are available via the server-side Auth API and the TypeScript SDK. For mobile apps, initiate the OAuth flow from your backend and exchange the resulting token for a Gate session on the server side. See the TypeScript SDK and Auth API reference for the full surface.


See also​

  • Auth API reference — Gate IAK full surface including MFA, social / OIDC / SAML, and admin recovery.
  • TypeScript SDK — server-side SDK with the complete auth surface.
  • Kibo — client-side BYOK/HYOK ZK sibling SDK (K9OKibo, same SwiftPM repository).
  • SDKs — all twelve v2 SDK languages.