Skip to content

Authentication ​

swift
// Account checks
public func checkEmailAvailability(email: String) async throws -> SB_EmailAvailabilityOutcome
public func validateAccountRequirements(
    _ request: SB_ValidateAccountRequirementsRequest
) async throws -> SB_ValidateAccountRequirementsResult

// SDK auth (externally-authenticated, password-less users — SB-957, SB-1933).
// Set `SB_SDK.sdkCredentials` from your backend's token exchange, then
// register with the user identity. Nothing else is a credential your
// backend minted — see §4.1.
public static var sdkCredentials: SB_SDKCredentials?         // org id + single-use token, from your backend
public typealias SB_SDKTokenProvider = @Sendable () async throws -> String
public func registerUser(
    userId: String,
    email: String? = nil,
    birthday: DateComponents? = nil,
    sex: SB_Gender? = nil,
    heightCm: Float? = nil,
    weightKg: Float? = nil,
    imperialUnits: Bool = false,
    activationCode: String? = nil,
) async throws -> SB_RegisterUserOutcome

// Session
public func hydrateSession()                                          // restore from keychain
public func signOut() async throws                                    // see side-effects note below
public func generateTemporaryAuthToken() async throws -> String?

// Password
public func requestPasswordReset(email: String) async throws -> SB_RequestPasswordResetOutcome  // ⚠️ link-based; slated for removal — see internal-only code-based reset below
public func changePassword(currentPassword: String, newPassword: String) async throws -> SB_ChangePasswordOutcome

// Agreements (ToS / Health Data)
public func shouldRequestAgreement(type: SB_AgreementType) async throws -> SB_AgreementCheck
public func acceptAgreements(tosVersion: String, healthDataVersion: String) async throws
public func acceptCurrentAgreements() async throws

signOut() side effects. A successful sign-out unlinks the paired device from the account server-side, disconnects any connected device, clears the paired-device state, nils out pairedDevice / haveDevice / exerciseZoneAttributes, and wipes the SDK's locally cached user data. The unlink is awaited before the logout RPC (it needs the session's credentials) and is best-effort — if it fails it is logged and the local teardown still completes, so the user is never stranded mid-sign-out. Signing out therefore costs the user their pairing: they re-pair the band on the next sign-in, which is deliberate and matches Android. signOut() is the only customer-facing way to clear SDK persistence — a wipe without a sign-out would leave in-memory @Published state and the BLE connection inconsistent with the cleared cache. Account-deletion flows should call signOut() after the delete-account call succeeds.

4.1 SDK registration (registerUser) ​

For third-party apps embedding the SDK, registerUser is a register-or-login entry point for users your app has already authenticated by its own means (your login, SSO, OAuth — the SDK doesn't care which). These users have no Sensor Bio email/password. On success the SDK persists the returned session and publishes session / userProfile. It is the only registration path in the distributed SDK — there is no email/password entry point.

Your backend mints a single-use token first. Your organization SDK Key (sbsk_…) is long-lived, org-wide, and identical for every one of your users, so it should be held by your backend and handed out as little as possible. Your backend exchanges it for a single-use, minutes-long sdk_token (sbst_…) and hands that to the app:

POST https://api.sensorbio.com/sdk/v1/token
Authorization: SDKKey sbsk_...
Content-Type: application/json

{}                                    # body optional; omit for the 5-minute default TTL
json
{
  "sdk_token": "sbst_...",
  "organization_id": "uuid",
  "sdk_key_id": "uuid",
  "expires_at": "2026-09-03T12:34:56Z",
  "expires_in_seconds": 300
}

sdk_token and organization_id are the only two fields your backend has to return to your app. The flow is: your backend authenticates its own user however it already does → it calls the exchange → it returns those two values to your app → your app passes them to the SDK. Staging is https://staging.api.sensorbio.com.

Building that endpoint: §5 covers it in full — the contract to serve your app, Node and Go implementations, every error the exchange returns and what to do about it, TTL choice, and how to rotate a key without signing your users out. The example app in this repo mocks that backend in-process so the SDK can be run without one; it is marked as a stand-in everywhere, because it holds an SDK Key on a device, which is the one thing the exchange exists to prevent.

A token is good for exactly one register-or-login and expires within minutes. Mint a fresh one for every registerUser call, and never cache or reuse one — a spent token fails inside registerUser as an authentication error, which is confusing to debug because the failure surfaces far from its cause. Revoking an SDK Key in the dashboard signs out every user currently signed in through it, on every device, in addition to preventing new sign-ins.

Set your credentials first. Immediately before registering, hand the SDK what your backend's token exchange returned:

swift
public struct SB_SDKCredentials: Sendable, Equatable {
    public let organizationId: String   // the `organization_id` the exchange returned
    public let sdkToken: String         // the single-use `sbst_…` token
    public init(organizationId: String, sdkToken: String)
}

let minted = try await myBackend.mintSensorBioToken()
SB_SDK.sdkCredentials = SB_SDKCredentials(
    organizationId: minted.organizationId,
    sdkToken: minted.sdkToken
)

Your organization SDK Key never reaches the device. That is the whole purpose of the exchange, and nothing in this SDK asks for one. Earlier versions did: an SB_SDKKeyCredentials whose sdk_token field in fact carried the raw key, presented on every authenticated call. Both it and sdkTokenProvider are removed (SB-2095).

The token is single use and is spent by the registerUser that follows, so this is set once per registration rather than held — the SDK clears it as it spends it, so a replay cannot happen quietly. The organization id is remembered across launches (an organization UUID is an identifier, not a secret), so a host relaunching into a restored session supplies nothing.

registerUser parameters:

  • userId — your own stable identifier for the end-user (client_sdk_user_id). The first call for a given userId registers; subsequent calls log in. It is also recorded as the user's username (visible in the web dashboard).
  • email (optional) — a contact email. Omitted if nil/empty; when supplied it is recorded on the backend as the user's contact email (never used as the login identity).
  • birthday / sex / heightCm / weightKg / imperialUnits (optional) — demographics. Any omitted value is filled with a dummy before the request is sent: the platform requires height/weight/sex/birthday to compute higher-level metrics (recovery, calories, sleep scoring, …), so a user with none would break downstream processing. Pass real values when you have them.
  • activationCode (optional) — redeems a device-subscription activation code during a first registration.

Everything that is not the user's identity comes from SB_SDK.sdkCredentials. If it is unset, registerUser returns .failure(errorCode: "sdkCredentialsNotSet"); if either field is empty, .failure(errorCode: "sdkCredentialsIncomplete").

swift
// SB_SDK.sdkCredentials must already be set (see above), carrying a token
// freshly minted for this one call.
switch try await sensorBio.registerUser(userId: userId) {
case .success(let session):        routeToHome(session)
case .failure(let errorCode):      showError(errorCode)   // e.g. "clientSdkUserIDAlreadyInUse"
}
swift
public enum SB_RegisterUserOutcome: Sendable {
    case success(SB_Session)
    case failure(errorCode: String)
}

When a session ends ​

If a session dies beyond recovery — its refresh token expired after 60 days of inactivity, its SDK Key was revoked, or the token itself was revoked — the SDK surfaces SB_AuthError.refreshTokenExpired. Treat it as a sign-out: mint fresh credentials, set SB_SDK.sdkCredentials, and call registerUser again with the same userId. Because registerUser is register-or-login on client_sdk_user_id, that returns the same user to the same data, and the server's login path echoes the stored profile rather than overwriting it with whatever demographics you pass.

The SDK deliberately does not do this for you. Rebuilding a session needs a freshly minted single-use token; the SDK cannot mint one, and an earlier version that kept a host closure around to mint from is exactly what required your SDK Key to be on the device.

What is transparent to your app, and what is not:

EventHandled byYour app sees
Access token expires (15 min)SDK refreshes and retriesNothing
Refresh token rotatesSDKNothing
Refresh chain dies (60-day inactivity, revoked, SDK Key revoked)YouSB_AuthError.refreshTokenExpired → mint fresh credentials, set sdkCredentials, registerUser again

Sensor Bio Mobile SDK — iOS & Android integration reference.