> 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/android-native/api-reference/authentication.md).

# Authentication

Authenticate the Android 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

```kotlin
val config = MultiSetSDKConfig.Builder("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET")
    .mapCode("YOUR_MAP_CODE")
    .build()
MultiSetSDK.initialize(applicationContext, config, callback)
```

The sample apps read them from `MULTISET_CLIENT_ID` and `MULTISET_CLIENT_SECRET` in `multiset.properties`.

{% 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 Android 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 `MultiSetSDKConfig.baseUrl` points at, `https://api.multiset.ai` unless you changed it.

### 2. App: pass a token provider

Build the config with `MultiSetSDKConfig.Builder(tokenProvider)` in place of the client ID and secret:

```kotlin
import com.multiset.sdk.MultiSetSDK
import com.multiset.sdk.MultiSetSDKConfig
import com.multiset.sdk.MultiSetTokenProvider
import com.multiset.sdk.MultiSetTokenRequestReason
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit

private val http = OkHttpClient.Builder().callTimeout(20, TimeUnit.SECONDS).build()

val tokenProvider = MultiSetTokenProvider { reason ->
    val forceNew = reason == MultiSetTokenRequestReason.REJECTED
    val request = Request.Builder()
        .url("https://api.example.com/multiset/token")
        .header("Authorization", "Bearer ${MyAppSession.accessToken}")
        .post("""{"forceNew":$forceNew}""".toRequestBody("application/json".toMediaType()))
        .build()
    http.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("Token endpoint answered HTTP ${response.code}")
        JSONObject(response.body!!.string()).getString("token")
    }
}

val config = MultiSetSDKConfig.Builder(tokenProvider)
    .mapCode("YOUR_MAP_CODE")
    .build()
MultiSetSDK.initialize(applicationContext, config, callback)
```

`MyAppSession.accessToken` stands for however your app proves its user to your API. You can also implement `MultiSetTokenProvider` in a class of your own; it is a suspending interface, so implement it in Kotlin.

The SDK passes a reason with each call:

| Reason     | When the SDK asks                                          | What to return                                                            |
| ---------- | ---------------------------------------------------------- | ------------------------------------------------------------------------- |
| `INITIAL`  | `MultiSetSDK.initialize`                                   | 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. Returning the refused token again fails the request |

* **Return only the token string.** The SDK reads the expiry from the token's `exp` claim.
* **The provider runs on a background thread**, so a blocking call like the one above is fine. A call that takes longer than 20 seconds fails; give your request a timeout of its own too.
* **Build the provider once, or make it a data class.** Calling `initialize` again with an equal provider, as an activity recreated by a rotation does, keeps the token the SDK already has.
* **A failed first token** (the provider throws or returns an empty string) reaches `onAuthenticationFailure(error)` as `"Token provider failed: …"`. To try again, call `MultiSetSDK.initialize` again.
* **A failed renewal** fails only the request that needed the new token. The next request asks your provider again, and a map upload retries it like a dropped connection.

### In the sample apps

Set `MULTISET_TOKEN_SERVER_URL` in `multiset.properties` to an endpoint that answers a GET with `{"token": "<JWT>"}`, and rebuild `:app` or `:xreal-aura-vps`. Each sample's `TokenServerProvider` adds `reason=initial`, `expiring` or `rejected` to the URL, and the sample then never uses `MULTISET_CLIENT_ID` or `MULTISET_CLIENT_SECRET`. A plain `http://` endpoint works only in debug builds.

## API

| Type                                       | Description                                                                                 |
| ------------------------------------------ | ------------------------------------------------------------------------------------------- |
| `MultiSetSDKConfig.Builder(tokenProvider)` | Starts a config that gets its tokens from `tokenProvider` instead of a client ID and secret |
| `MultiSetSDKConfig.tokenProvider`          | The provider in use, or `null` with client credentials                                      |
| `MultiSetTokenProvider`                    | Interface with one method, `suspend fun token(reason: MultiSetTokenRequestReason): String`  |
| `MultiSetTokenProvider { reason -> }`      | Makes a `MultiSetTokenProvider` from a suspending lambda                                    |
| `MultiSetTokenRequestReason`               | `INITIAL`, `EXPIRING` or `REJECTED`                                                         |


---

# 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/android-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.
