> For the complete documentation index, see [llms.txt](https://docs.multiset.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/authentication.md).

# Authentication

Authenticate the iOS SDK with your client ID and secret, or keep the secret on your server and give the SDK a token provider.

Every request the SDK sends to the MultiSet API carries a short-lived access token (a JWT). The SDK gets its tokens in one of two ways:

| Method                                    | How the SDK gets tokens                            | Use it for                    |
| ----------------------------------------- | -------------------------------------------------- | ----------------------------- |
| [Client credentials](#client-credentials) | Exchanges your client ID and secret itself         | Development and internal apps |
| [Token provider](#token-provider)         | Asks your app, which fetches them from your server | Apps you publish              |

Your client ID and secret are on the **Credentials** page of the [Developer Portal](https://developer.multiset.ai/credentials). See [Credentials](https://docs.multiset.ai/fundamentals/credentials.md).

With either method the SDK renews tokens before they expire, retries a request refused with HTTP 401 once with a new token, and shares one renewal between requests made at the same time. Map uploads use the same tokens.

## Client credentials

```swift
let config = MultiSetConfig(
    clientId: "YOUR_CLIENT_ID",
    clientSecret: "YOUR_CLIENT_SECRET",
    mapCode: "YOUR_MAP_CODE"
)
MultiSet.shared.initialize(config: config, callback: self)
```

{% hint style="warning" %}
The client secret ships inside your app, where anyone who unpacks the app can read it. Use a token provider for apps you publish.
{% endhint %}

## Token provider

{% hint style="info" %}
Requires iOS SDK 2.2.0 or later.
{% endhint %}

The client ID and secret stay on your server:

1. Your app asks your API for a MultiSet token, signed in as your user.
2. Your server gets a token from `POST /v1/m2m/token` with the client ID and secret, and returns it.
3. The SDK sends the token on every MultiSet request, and asks your app again whenever it needs a new one.

### 1. Server: hand out tokens

Your server requests a token with Basic authentication, as in [REST API Authentication](https://docs.multiset.ai/fundamentals/rest-api-docs/authentication.md):

```bash
curl -X POST https://api.multiset.ai/v1/m2m/token -u "$MULTISET_CLIENT_ID:$MULTISET_CLIENT_SECRET"
# {"token": "<JWT>", "expiresOn": "2026-11-03T11:36:01.356Z"}
```

Expose an endpoint that returns one to your signed-in users. A minimal example in Node.js 18+ with Express:

```js
const express = require("express");

const app = express();
app.use(express.json());

const basicAuth = Buffer.from(
  `${process.env.MULTISET_CLIENT_ID}:${process.env.MULTISET_CLIENT_SECRET}`
).toString("base64");
const FIVE_MINUTES = 5 * 60 * 1000;
let cached = null; // { token, expiresOn }

async function newMultiSetToken() {
  const response = await fetch("https://api.multiset.ai/v1/m2m/token", {
    method: "POST",
    headers: { Authorization: `Basic ${basicAuth}` },
  });
  if (!response.ok) throw new Error(`MultiSet token request failed: HTTP ${response.status}`);
  cached = await response.json();
  return cached;
}

// requireSignedInUser is your own sign-in middleware.
app.post("/multiset/token", requireSignedInUser, async (req, res) => {
  try {
    const stillGood = cached && Date.parse(cached.expiresOn) - Date.now() > FIVE_MINUTES;
    res.json(req.body?.forceNew || !stillGood ? await newMultiSetToken() : cached);
  } catch {
    res.status(502).json({ error: "MultiSet token unavailable" });
  }
});
```

* **Keep the secret on the server**, in an environment variable or a secret manager.
* **Require your own sign-in, over HTTPS.** Whoever holds a token can call the MultiSet API as your account until it expires.
* **Issue a new token when the app asks after a refusal** (`forceNew` above). Otherwise a cached token is fine; the example replaces it once it has less than 5 minutes left.
* **Use the app's environment.** Request tokens from the host that `MultiSetConfig.baseURL` points at, `https://api.multiset.ai` unless you changed it.

### 2. App: pass a token provider

Pass `.tokenProvider` in place of the client ID and secret:

```swift
import MultiSetSDK

let tokenProvider = ClosureTokenProvider { reason in
    var request = URLRequest(url: URL(string: "https://api.example.com/multiset/token")!,
                             timeoutInterval: 20)
    request.httpMethod = "POST"
    request.setValue("Bearer \(MyAppSession.accessToken)", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(["forceNew": reason == .rejected])

    let (data, response) = try await URLSession.shared.data(for: request)
    guard (response as? HTTPURLResponse)?.statusCode == 200 else {
        throw URLError(.badServerResponse)
    }

    struct TokenResponse: Decodable { let token: String }
    return try JSONDecoder().decode(TokenResponse.self, from: data).token
}

let config = MultiSetConfig(credentials: .tokenProvider(tokenProvider), mapCode: "YOUR_MAP_CODE")
MultiSet.shared.initialize(config: config, callback: self)
```

`MyAppSession.accessToken` stands for however your app proves its user to your API. You can also conform a type of your own to `MultiSetTokenProvider` instead of using `ClosureTokenProvider`.

The SDK passes a reason with each call:

| Reason      | When the SDK asks                                          | What to return                         |
| ----------- | ---------------------------------------------------------- | -------------------------------------- |
| `.initial`  | `initialize(config:callback:)`                             | A valid token                          |
| `.expiring` | The first request near the end of the current token's life | A valid token; a cached one is fine    |
| `.rejected` | The API refused the current token with HTTP 401            | A newly issued token, not a cached one |

* **Return only the token string.** The SDK reads the expiry from the token's `exp` claim.
* **Await your request; don't block.** The provider is called on the main actor, one call at a time. The SDK does not time the call out, so give your request a timeout. `MultiSet.shared.release()` cancels a call in flight.
* **A failed first token** (the provider throws or returns an empty string) reaches `onAuthenticationFailure(error:)` as `"Token provider failed: …"`. A second `initialize` is ignored while the SDK is initialized, so to try again call `MultiSet.shared.release()` and then `initialize(config:callback:)`.
* **A failed renewal** fails only the request that needed the new token. The next request asks your provider again.

### In the sample app

Set `tokenServerURL` in `MultiSet-SDK-Samples/SDKConfig.swift` of the [sample app](https://github.com/MultiSet-AI/multiset-swift-samples) to an endpoint that answers a GET with `{"token": "<JWT>"}`. The sample's `TokenServerProvider` adds `?reason=initial`, `expiring` or `rejected` to the URL, and the sample then never uses its `clientId` or `clientSecret`.

## API

| Type                         | Description                                                                                                                               |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `MultiSetCredentials`        | `.clientCredentials(clientId:clientSecret:)` or `.tokenProvider(_:)`, passed to `MultiSetConfig(credentials:mapCode:mapSetCode:baseURL:)` |
| `MultiSetTokenProvider`      | Protocol with one method, `token(for:) async throws -> String`, called on the main actor                                                  |
| `ClosureTokenProvider`       | A `MultiSetTokenProvider` made from a closure                                                                                             |
| `MultiSetTokenRequestReason` | `.initial`, `.expiring` or `.rejected`                                                                                                    |
| `MultiSetConfig.credentials` | The credentials in use. `clientId` and `clientSecret` read as empty with a token provider                                                 |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.multiset.ai/native-sdk/ios-swift-native/api-reference/authentication.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
