Skip to main content
Swift SDK / Custom Authenticator For shipped iOS apps, don’t embed your long-lived projectKey in the binary. Instead, implement the Authenticator protocol so the SDK fetches a short-lived bearer token from your backend whenever it needs one.

The protocol

The native runtime calls getAuthHeader() whenever it needs a fresh token for an outbound request, and it calls it on every request. The SDK does not cache delegated tokens for you, so your implementation should cache the token and refetch only when it’s near expiry (see Token caching). The method may be called from any thread. After a 401 from the Moss service, the SDK calls getAuthHeader() again and retries the request once with the token it returns. It doesn’t tell your authenticator which token was rejected.

Return-value contract

Return the raw bearer token only - do not include the Bearer prefix. The SDK constructs the full Authorization: Bearer <token> header itself.
The JavaScript SDK’s IAuthenticator.getAuthHeader() returns the full Bearer ... value, but the JavaScript SDKs never call it. They call getAuthToken(), whose token is the raw token this method returns.

Token caching

Unlike the project-key initializer (which caches tokens internally) and the JavaScript SDK (which wraps your authenticator in an automatic cache), the Swift Authenticator returns only a token string. The runtime has no expiry to cache against, so caching is your responsibility. Have your backend return the token’s lifetime alongside it, cache both on-device, and return the cached token until it’s close to expiry. The example keeps a token until 60 seconds before it expires, or for 90% of its life when that is later, the rule the project-key initializer uses:
Your token endpoint should return JSON shaped like { "token": "...", "expiresIn": 3600 } (expiresIn in seconds). With caching in place your backend is hit only on a cold start and once per token lifetime. Every request in between gets its token from the in-memory cache.
A complete, runnable example (the iOS app plus a token-vending backend in Node and Python) is in examples/ios in the Moss repo.
See MossClient for the matching initializer.