# Authentication in the SDK

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

Mint session tokens on your server, keep them fresh in a Swift app, open share links and act as a member.

An app holds a publishable key and a session token your server mints. The client keeps the token fresh and sends both on every request. [Authentication](https://docs.mountaya.com/en/authentication.md) explains the credentials themselves.

## Mint on your server

Your server mints a session token with its secret key, through the admin product:

```swift
import Foundation
import MountayaAdmin
import MountayaClient

// The body of your POST /session route. `userId` comes from your own sign-in, never the request.
func mintSession(for userId: String) async throws -> RestSchema.Session {
  let environment = ProcessInfo.processInfo.environment
  let server = try Mountaya(credential: .secret(key: environment["MOUNTAYA_SECRET_KEY"] ?? ""))
  let minted = try await server.admin.sessions.postSession(
    body: .init(publishable_key: environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? "") {
      $0.user_id = userId
    })
  return minted.data
}
```

Answer the app with `JSONEncoder().encode(session)`.

## Keep the token fresh in the app

`SessionTokenEngine` asks your server for a token, and asks again before it expires. The app reads your server's address, `MOUNTAYA_SESSION_URL`, from Info.plist:

```swift
import Foundation
import MountayaClient

let info = Bundle.main.infoDictionary ?? [:]
let sessionURL = URL(string: info["MOUNTAYA_SESSION_URL"] as? String ?? "")

let sessions = SessionTokenEngine {
  guard let sessionURL else { throw URLError(.badURL) }
  var request = URLRequest(url: sessionURL)
  request.httpMethod = "POST"
  let (body, _) = try await URLSession.shared.data(for: request)
  return try JSONDecoder().decode(RestSchema.Session.self, from: body)
}
let mountaya = try Mountaya(
  credential: .publishable(
    key: info["MOUNTAYA_PUBLISHABLE_KEY"] as? String ?? "", sessionToken: .source(sessions)))
```

A request waits for the first token. Each later request sends the token the engine holds.

- `MOUNTAYA_SESSION_URL` is your server's `POST /session` route (`http://127.0.0.1:8787/session` as the Trail apps run it, from the iOS simulator), answering the session as JSON with `Cache-Control: no-store` ([server quickstart](https://docs.mountaya.com/en/sdks/swift/quickstart-server.md#serve)). The build writes it into Info.plist from `Local.xcconfig`, where `//` starts a comment: write `http:/$()/127.0.0.1:8787/session`. Plain HTTP to a local address needs an App Transport Security exception for it alone.
- The engine mints through the function you give it, then mints the next token 60 seconds before the last expires, or halfway through a shorter life, from each mint's `expires_at`. It never mints in answer to a `401`.
- A mint that fails keeps the token held and is tried again 5 seconds later, each failure in a row waiting twice as long, up to 60 seconds; a timeout counts as a failure. A mint your app cancels mints nothing more until `refresh()`, `enable()` or a new subscription asks.
- The engine runs only while something holds it: a `Mountaya` built over it holds it for as long as the client lives. `disable()` stops it, `enable()` starts it again, `refresh()` mints now.
- `snapshot` is a `SessionSnapshot` (`token`, `expiresAt`, `userId`, `isMinting`, `error`), and `subscribe()` an `AsyncStream<SessionSnapshot>` of every change, for a view that shows the session's state.
- `SessionTokenEngine(mint:clock:wallClock:)` takes the clocks a test pins.
- A token can also be a plain value (`.value("sess_your_session_token")` or a string literal), `.minted(session)`, `.function { … }` read per request, or any `SessionTokenSource`.
- A credential prints each key's and token's prefix and `…`, never the rest; a minted session's `token` prints `<redacted>`.

## Open a shared itinerary

A share link carries a share token. It replaces the key, so a visitor needs no key and no session:

```swift
import Foundation
import MountayaClient

// The share link the visitor opened.
let link = URLComponents(string: "https://example.com/tour?share_token=share_your_share_token")
let shareToken = link?.queryItems?.first { $0.name == "share_token" }?.value ?? ""

let visitor = try Mountaya(credential: .share(token: shareToken))
let itinerary = try await visitor.studio.itineraries.getItinerary(
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21")
print(itinerary.data.name)
```

A map built over that client draws the shared itinerary the same way.

- `Credential(publishableKey:sessionToken:shareToken:)` builds a credential from parts held apart (a key from configuration, a token from a link) and applies "a share token replaces the key" itself: given both, it sends the share token alone. Parts that make no credential, a session token with no key, throw `MountayaError.configuration`.
- `.share(token:cookies:)`: a share link that rides the visitor's own session takes its `Cookie` header from the `CookieSource` you pass, per request. Reads (every Data API query and any `GET`, `HEAD` or `OPTIONS`) go out on that session alone; a write under a share token is refused.
- `credential.headers(for:language:method:)` answers the headers a credential sends to an operation.
- A map whose client holds a share token puts `share_token` in its tile URLs, which the Tile API accepts. Such a map reads no organization: `loadOrganization()` answers nil.

## Act as a member

A write acts as a member of your organization. Mint the session for the `studio-embedded` product and name the member, then write with it:

```swift
import Foundation
import MountayaAdmin
import MountayaClient

let environment = ProcessInfo.processInfo.environment
let publishableKey = environment["MOUNTAYA_PUBLISHABLE_KEY"] ?? ""
let server = try Mountaya(credential: .secret(key: environment["MOUNTAYA_SECRET_KEY"] ?? ""))
let session = try await server.admin.sessions.postSession(
  body: .init(publishable_key: publishableKey) {
    $0.surface = .studioEmbedded
    $0.user_id = "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1"
  }
).data

let member = try Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: .minted(session)))
let renamed = try await member.studio.itineraries.patchItinerary(
  itinerary_id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
  body: .init { $0.name = "Tour du Mont-Blanc, summer" })
print(renamed.data.name)
```

The publishable key needs the `studio-embedded` scope. Every write made under that token is that member's.

- A write under a token minted for any other product (`api` among them), or one minted without `user_id`, is refused `401`: `MountayaError.api` whose `kind` is `.authentication`.
- The mint is refused `402` (`.billing`) while the organization does not hold Embedded Studio, and `403` (`.forbidden`) for a key without the `studio-embedded` scope.
- An editor's event stream (`mountaya.studio.collab.getItineraryEvents(itinerary_id:)`) is read as its member's user, the one the session token names. Where the token names none (a token given as a plain value), name the user with `.reading(asUser:)` on the stream, so that member's own arrival is not read as the stream moving on.
- `RestSchema.SessionSurface` members are lowerCamelCase: `.studioEmbedded`, `.api`.

## Keep the secret key out of the app

`.secret(key:)` exists only on macOS and Linux. An iOS, iPadOS, tvOS, watchOS, visionOS or Mac Catalyst build cannot name it, so the compiler stops a secret key from shipping in an app:

```swift
import Foundation
import MountayaClient

// Compiles for a server on macOS or Linux. In an iOS app, the compiler refuses `.secret`.
let environment = ProcessInfo.processInfo.environment
let server = try Mountaya(credential: .secret(key: environment["MOUNTAYA_SECRET_KEY"] ?? ""))
```

Keep the secret key in your server's environment, and never in Info.plist or an xcconfig.

- The barrier is `@available(iOS, unavailable, message: "A secret key belongs on a server, never in an app.")`, with the same for Mac Catalyst, tvOS, visionOS and watchOS, on `Credential.secret(key:)` and `Credential.init(secretKey:publishableKey:sessionToken:shareToken:)`. `constructWebhookEvent` carries the same barrier.
- Swift has no browser build, so the contract's browser refusal of a secret key does not apply here; the platform barrier stands in its place. The prefix check (a secret key starts `sk_`) still runs where the client is built.
- A secret key authenticates `postSession` and nothing else. It never reaches a device: mint session tokens and make every other call with the publishable key beside one.

## Next steps

- [Client basics](https://docs.mountaya.com/en/sdks/swift/client.md): Every API, writes, field selection and streams.
- [Manage an organization](https://docs.mountaya.com/en/sdks/swift/admin.md): Members, keys, sessions and webhook endpoints.
