# Authentication in the SDK

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

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

The publishable key goes in every client. A session token goes beside it for the Data API, for drafts and for every write. Your server mints the token with the secret key, and the app keeps it fresh.

## Mint on your server

Call `postSession` with your secret key, for the user your own sign-in names:

```dart
import 'dart:io';

import 'package:mountaya_admin/admin_schema.dart' as admin_schema;
import 'package:mountaya_admin/mountaya_admin.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;

final environment = Platform.environment;
final server = Mountaya(
  credential: SecretCredential(environment['MOUNTAYA_SECRET_KEY'] ?? ''),
);

// What your session route answers, as JSON: token, expires_at, user_id.
Future<rest_schema.Session> mintSession(String userId) async {
  final minted = await server.admin.sessions.postSession(
    body: admin_schema.SessionCreateParams(
      publishable_key: environment['MOUNTAYA_PUBLISHABLE_KEY'] ?? '',
      // The member your own sign-in vouches for, never one the request names.
      user_id: userId,
    ),
  );
  return minted.data;
}

final session = await mintSession('7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1');
print(session.expires_at);
await server.close();
```

Your session route answers `session.toJson()`; the [server quickstart](https://docs.mountaya.com/en/sdks/dart/quickstart-server.md#serve) serves it at `POST /session`.

- `postSession` is `POST /v1/sessions` on the Map Studio API, under `admin.sessions` once `package:mountaya_admin/mountaya_admin.dart` is imported. Body `admin_schema.SessionCreateParams`: `publishable_key` (required), `user_id` (optional, the member the token acts as), `surface` (optional: `rest_schema.SessionSurface.api`, the default, or `studioEmbedded`). It answers a `rest_schema.Session`: `token`, `expires_at`, `user_id`. Answer `session.toJson()` from your route so the app reads it back with `rest_schema.Session.fromJson`.
- A secret key authenticates `postSession` and nothing else. The client refuses it on any other operation with `ConfigurationException` before sending. Only the key's prefix is checked locally: a well-formed but wrong key answers `401`.
- A token lives at most five minutes (`expires_at`). Never cache the route's answer: `Cache-Control: no-store`.
- `user_id` must be a member of the key's organization or hold an invitation to it; any other answers `403`, held to a rate limit of its own.

## Keep the token fresh in the app

Give the client a `SessionTokenEngine`. It calls your route, and mints again before each token expires:

```dart
import 'dart:convert';
import 'dart:io';

import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;

const publishableKey = String.fromEnvironment('MOUNTAYA_PUBLISHABLE_KEY');
const sessionUrl = String.fromEnvironment('MOUNTAYA_SESSION_URL');

// Posts to your session route and reads the session it answers.
Future<rest_schema.Session> mintSession() async {
  final http = HttpClient();
  try {
    final request = await http.postUrl(Uri.parse(sessionUrl));
    final response = await request.close();
    final body = await response.transform(utf8.decoder).join();
    if (response.statusCode != HttpStatus.ok) {
      throw HttpException('The session route answered ${response.statusCode}.');
    }
    return rest_schema.Session.fromJson(jsonDecode(body));
  } finally {
    http.close();
  }
}

final sessions = SessionTokenEngine(mint: mintSession);
final mountaya = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: .source(sessions)),
);
await mountaya.close();
```

One client serves the whole app. Each request, and each map tile, carries the current token. Call `sessions.refresh()` after your user signs in, and `sessions.disable()` when they sign out.

- The engine mints 60 seconds before the token expires, or halfway through a shorter life, never on a `401`. It runs only while something listens to its `subscribe()` stream, which a `Mountaya` built over it does until the client is closed, so a headless app that never draws still keeps its session.
- A mint that fails (a `TimeoutException` from a deadline your own call set among the failures) is tried again 5 seconds later, each next wait twice the one before, up to 60 seconds; a token that arrives already spent counts the same. A mint that throws `AbortedException` (an `AbortSignal` aborted with no reason), or `package:http`'s `RequestAbortedException`, is a cancellation: it waits for `refresh()`, `enable()` or a new listener.
- `mint` is settable: the next mint calls the function you set, and setting one mints nothing. `refresh()` mints at once. `disable()` clears the token, its expiry and its user, so a signed-out user's credential cannot be read off `snapshot`; `enable()` resumes.
- `snapshot` is a `SessionSnapshot`: `token`, `expiresAt`, `userId`, `isMinting`, `error`.
- A session token can also be `.value(token)` (fixed: every call after its expiry is a `401`), `.minted(session)` (one `rest_schema.Session`), `.function(read)` (read on each request) or `.source(source)`, any `SessionTokenSource`. `MapEngine` refuses a client whose token is `.function(...)` with `ConfigurationException`: the map's request hook needs values set between requests.
- `sessionUrl` comes from `--dart-define-from-file=.env` as Trail's `MOUNTAYA_SESSION_URL` does: `http://localhost:8787/session` from the iOS simulator, `http://10.0.2.2:8787/session` from the Android emulator. Android lets a debug build send plain HTTP, and a release build none.
- Without the SDK, send `X-API-Key` and `X-Session-Token` on each request, and mint again about a minute before `expires_at`.

## Open a shared itinerary

A share link carries a share token, which replaces the key for its visitor:

```dart
import 'package:mountaya_client/mountaya_client.dart';

// Read from the share link your visitor opened.
const shareToken = 'share_your_share_token';

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

`Credential(publishableKey:, shareToken:)` builds the credential from parts you hold apart, and sends the share token alone when both are set.

- `.share(token:)` builds a `ShareCredential`. A share token reaches the one itinerary or collection its link shares, reads only, and a write under it is refused.
- `Credential(publishableKey:, sessionToken:, shareToken:)` 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 Mountaya session takes its `Cookie` header from the `cookies:` function you pass `.share(token:, cookies:)`, read per request.
- A share token is created by `postItineraryShareLink` (`rest_schema.ShareLink.share_token`), rotated by `postItineraryShareLinkRotate`, and removed by `deleteItineraryShareLink`.
- `MapEngine` takes a share credential: its tile requests carry the share token.

## Act as a member

A token minted without `user_id` reads only what your organization publishes, and writes nothing. To write, mint the token for the member your own sign-in vouches for:

```dart
import 'dart:io';

import 'package:mountaya_admin/admin_schema.dart' as admin_schema;
import 'package:mountaya_admin/mountaya_admin.dart';
import 'package:mountaya_client/mountaya_client.dart';
import 'package:mountaya_client/rest_schema.dart' as rest_schema;

final environment = Platform.environment;
final publishableKey = environment['MOUNTAYA_PUBLISHABLE_KEY'] ?? '';
final server = Mountaya(
  credential: SecretCredential(environment['MOUNTAYA_SECRET_KEY'] ?? ''),
);
final minted = await server.admin.sessions.postSession(
  body: admin_schema.SessionCreateParams(
    publishable_key: publishableKey,
    user_id: '7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1',
    surface: rest_schema.SessionSurface.studioEmbedded,
  ),
);

// Every call with this token acts as that member.
final member = Mountaya(
  credential: .publishable(key: publishableKey, sessionToken: .minted(minted.data)),
);
final renamed = await member.studio.itineraries.patchItinerary(
  itinerary_id: '0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21',
  body: rest_schema.ItineraryUpdateParams(name: 'Tour du Mont-Blanc, summer'),
);
print(renamed.data.name);
await member.close();
await server.close();
```

Read the member's id from your server's own session, never from the request.

- No header names a user: the session token is the whole statement of who a call acts as. A token minted without `user_id` reads as the public does and writes nothing.
- A write to an itinerary, a collection or a zone takes a token minted for `rest_schema.SessionSurface.studioEmbedded`, naming the member, beside a publishable key carrying the `studio-embedded` scope (which also carries `tiles` and `data`). A token minted for any other surface is refused there with `401`. The organization must hold Embedded Studio, or the mint is refused with `402`; a key without the scope has it refused with `403`.
- An operation whose credential declaration requires an acting user, every write and every read under `/v1/me`, answers `401` under a token minted without `user_id`. The client refuses it locally with `ConfigurationException` when a session engine or a minted session states the token was minted without `user_id` (`user_id` is `null`); for a token held as `.value(...)` it cannot tell, so the API answers.
- A `403` under a member token means the member lacks the role the call asks, or the key lacks the scope.
- When the person changes, mint for the new person: a token names one member for its whole life. The collaboration stream takes `readingAsUser(userId)` where a `.value(...)` token cannot say whom it names.

## Keep the secret key out of the app

`SecretCredential` exists on the Dart VM only. In a Flutter build the name does not exist, so code that holds a secret key does not compile, and no key can ship inside an app.

- The barrier is a conditional export: the core's barrel reaches `SecretCredential` only where `dart:ui` is not available, so every Flutter build (Android and iOS, debug and release) leaves it out. The admin unit's barrel does the same for `constructWebhookEvent`, so an endpoint's signing secret never ships in an app either.
- The Dart VM (a server, a command-line tool, `dart test`) keeps both.
- `transport.browser.secret-key` is scoped in this SDK: no web build is published, so there is no browser to refuse a key in. The prefix check (`sk_`) and the server-only guidance remain.
- An app holds a publishable key alone, with no `management` scope, and asks its server for session tokens.

## Next steps

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