# Authentication in the SDK

> Canonical URL: https://docs.mountaya.com/en/sdks/kotlin/authentication/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Mint session tokens on your JVM server, keep them fresh in the app with SessionTokenEngine, open share links, and keep the secret key off devices.

An app holds a publishable key and a session token your server mints. The server holds the secret key, which no Android or iOS build can even name.

## Mint on your server

On the JVM, a client over the secret key mints a token for the member your own sign-in vouches for:

```kotlin
import com.mountaya.admin.admin
import com.mountaya.admin.generated.AdminSchema
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.RestSchema

// `server` is built with Credential.Secret. `userId` is the member your own sign-in vouches for.
suspend fun mintFor(server: Mountaya, publishableKey: String, userId: String): RestSchema.Session =
    server.admin.sessions
        .postSession(AdminSchema.SessionCreateParams(publishable_key = publishableKey) { user_id = userId })
        .data
```

Answer the app with that `Session` as JSON. The [server quickstart](https://docs.mountaya.com/en/sdks/kotlin/quickstart-server.md#serve) serves it.

- `postSession` is the one operation a secret key authenticates. It answers `RestSchema.Session`: `token`, `expires_at`, `user_id`.
- `user_id` is read from your server's session, never from the request. Left out, the token is minted without `user_id`: it reads as the public and writes nothing.
- The `surface` builder member says what the token is for: the default `api`, or `RestSchema.SessionSurface.StudioEmbedded` for a token that writes (see [act as a member](https://docs.mountaya.com/en/sdks/kotlin/authentication.md#act-as-member)).
- Errors of the mint: `AuthenticationException` (`401`) for a wrong secret key, `BillingException` (`402`) where the organization lacks the product the surface needs, `ForbiddenException` (`403`) for a publishable key without the scope.

## Keep the token fresh in the app

`SessionTokenEngine` mints through your server and refreshes before each token expires. Hand it to the client as the token's source:

```kotlin
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya
import com.mountaya.client.SessionToken
import com.mountaya.client.SessionTokenEngine
import com.mountaya.client.generated.RestSchema
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import java.net.HttpURLConnection
import java.net.URI

class TrailViewModel : ViewModel() {
    private val sessions = SessionTokenEngine(viewModelScope, mint = { fetchSession() })

    val mountaya = Mountaya(Credential.Publishable(BuildConfig.MOUNTAYA_PUBLISHABLE_KEY, SessionToken.Source(sessions)))

    override fun onCleared() = mountaya.close()

    // Your server answers the Session that postSession minted.
    private suspend fun fetchSession(): RestSchema.Session =
        withContext(Dispatchers.IO) {
            val connection = URI.create(BuildConfig.MOUNTAYA_SESSION_URL).toURL().openConnection() as HttpURLConnection
            connection.requestMethod = "POST"
            connection.doOutput = true
            connection.setRequestProperty("Content-Type", "application/json")
            connection.outputStream.use { it.write("{}".encodeToByteArray()) }
            val body = connection.inputStream.use { it.readBytes().decodeToString() }
            Json { ignoreUnknownKeys = true }.decodeFromString(RestSchema.Session.serializer(), body)
        }
}
```

A request made before the first token waits for it. Call `sessions.refresh()` after a sign-in, and `sessions.disable()` on a sign-out.

- `SessionTokenEngine(scope, mint)` runs in the scope you give it and mints only while something collects its `snapshot`, a `StateFlow<SessionSnapshot>` (`token`, `expiresAt`, `userId`, `isMinting`, `error`). A `Mountaya` built over `SessionToken.Source(engine)` collects it until the client is closed.
- It mints the next token 60 seconds before the last expires, or halfway through a shorter life, from each mint's `expires_at`, never after a `401`. A request made while the first mint is out waits for it, within the attempt's timeout.
- A failed mint keeps the token held and records the failure in `snapshot.value.error`. It is tried again after 5 seconds, each failure in a row waiting twice as long, up to 60 seconds; a timeout your `mint` set with `withTimeout` counts. A mint your app cancels waits for `refresh()`, `enable()` or a new subscription.
- Once no mint is on its way, a call that requires a session (every Data API call) is refused with `ConfigurationException` whose `cause` is the mint's failure; any other call is sent under the key alone.
- `refresh()` mints now. `disable()` stops minting and clears the token and its user; `enable()` lets it mint again. Assigning `engine.mint` mints nothing, so a composable passing a new lambda on each recomposition costs no call.
- The other ways to give a token: `SessionToken.Value("sess_…")` (a value, which expires within minutes and does not tell the client whom it names), `SessionToken.Minted(session)`, `SessionToken.Function { … }` read on every request, and `SessionToken.Source(source)` over any `SessionTokenSource` of your own.
- When the signed-in member changes, call `refresh()` once your server answers for the next member, and make a new `ItineraryResourceCache`, which keeps what the member before read.

## Open a shared itinerary

A visitor holding a share link reads the shared resource with its token in place of the key:

```kotlin
import com.mountaya.client.Credential
import com.mountaya.client.Mountaya

// The token at the end of the share link the visitor opened.
suspend fun openShared(shareToken: String = "share_your_share_token") {
    val visitor = Mountaya(Credential.Share(shareToken))
    val itinerary = visitor.studio.itineraries.getItinerary("0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
    println(itinerary.data.name)
    visitor.close()
}
```

- A share token replaces the publishable key. It reads the shared itinerary or collection, and the client refuses every write under it with `ConfigurationException` before sending.
- `Credential(publishableKey = …, sessionToken = …, shareToken = …)` builds a credential from parts held apart, a key from configuration and a token from a link, and applies "a share token replaces the key" itself. Parts that make no credential (a session token with no key) are a `ConfigurationException`.
- A share link that rides the visitor's own web session takes its `Cookie` header from `Credential.Share(token, cookies = { url -> … })`, per request: a read (`GET`, `HEAD`, `OPTIONS`, or an operation declared a read, every Data API query among them) goes out on the visitor's session alone, and a write is refused.
- A map over a share token draws the shared resource: `MapEngine(Mountaya(Credential.Share(token)))`.

## Act as a member

A write, a collaboration stream or an agent run acts as a member. Mint its token for that member and for Embedded Studio:

```kotlin
import com.mountaya.admin.admin
import com.mountaya.admin.generated.AdminSchema
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.RestSchema

suspend fun mintWriter(server: Mountaya, publishableKey: String): RestSchema.Session =
    server.admin.sessions
        .postSession(
            AdminSchema.SessionCreateParams(publishable_key = publishableKey) {
                user_id = "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1"
                surface = RestSchema.SessionSurface.StudioEmbedded
            },
        ).data
```

The app's client then writes as that member:

```kotlin
import com.mountaya.client.Mountaya
import com.mountaya.client.generated.RestSchema

suspend fun rename(mountaya: Mountaya) {
    val renamed =
        mountaya.studio.itineraries.patchItinerary(
            "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
            body = RestSchema.ItineraryUpdateParams { name = "Tour du Mont-Blanc, summer" },
        )
    println(renamed.data.name)
}
```

- Every call that acts as a member (each write, the collaboration and agent streams, the membership read) needs a token minted with `user_id`, a publishable key carrying the `studio-embedded` scope, and `surface = RestSchema.SessionSurface.StudioEmbedded`.
- A token minted for any other surface, `api` among them, is an `AuthenticationException` (`401`) on a write. The mint itself is a `BillingException` (`402`) where the organization lacks Embedded Studio, and a `ForbiddenException` (`403`) for a key without `studio-embedded`.
- Under a token the client knows is minted without `user_id` (an engine's, or a minted `Session`), the client refuses such a call with `ConfigurationException` before sending. A token given as `SessionToken.Value` is sent, and the API answers `401`.
- An editor stream is read as its member's user: `client.studio.collab.getItineraryEvents(id).readingAsUser(userId)`, applied before any other operator. The user a minted session or an engine names wins over the one it states.
- Never write unless the user asked for that write. A publish (`postItineraryPublication`) freezes the draft that readers are served and counts against the published itineraries the agreement allows.

## Keep the secret key out of the app

`Credential.Secret` and `Credential(secretKey = …)` are declared on the JVM alone. An Android or iOS build has no symbol to call, so a secret key cannot ship in an app by mistake.

- The compile-time barrier: `Credential.Secret`'s factory is the jvm-only extension `com.mountaya.client.invoke` (file facade `SecretKeyCredential`), and `Credential(secretKey = …)` is jvm-only too. In `commonMain`, `androidMain` or an iOS source set the call does not resolve. This replaces the TypeScript SDK's browser refusal, `transport.browser.secret-key`, which this SDK scopes: it publishes no browser target.
- A JVM desktop app can still build one: only a server mints session tokens, and an app asks that server for them. The same holds for `constructWebhookEvent` and a webhook endpoint's signing secret, also jvm only.
- The client refuses a secret key for any operation but `postSession`, and a publishable key or a share token in its place, with `ConfigurationException`, before any request.
- Credentials are checked where they are built and before each request. A header carries printable ASCII alone: a key or a token holding another character, `…` or `é`, is refused as `ConfigurationException`, its value never written out.

## Next steps

- [Client basics](https://docs.mountaya.com/en/sdks/kotlin/client.md): The three APIs, writes, streams and answers.
- [Manage an organization](https://docs.mountaya.com/en/sdks/kotlin/admin.md): Members, keys and webhook endpoints from a server.
