Sign in from a native app #

View this page as Markdown

On this page

Prompt:

Let the users of our iPhone and Android app sign in to the backend on Turn Zero Cloud.

Also works:

  • "Our Expo app needs sign-in."
  • "Keep app users signed in for months."
  • "The app must confirm it is really the user before deleting the account."

The app signs its users in through the system browser sheet and keeps the session token and refresh credential it gets back. It sends the token to your backend on every call as the bearer, in the header Authorization: Bearer <token>. Three steps set it up: declare the app on the realm (step 1), add the sign-in module to the app (step 2), and send the token on each backend call (step 5).

What your AI tool does #

  • Reads the mobile-backend skill (read_context, id skill:mobile-backend) and follows it.
  • Copies the sign-in module of step 2 into the app and connects it to the app's browser sheet, secure store, and crypto.
  • Opens the sign-in at /__account/oauth/authorize with response_type=code, the client_id, one declared redirect_uri, the code_challenge under code_challenge_method=S256, and a state, then exchanges the code as step 3 describes.
  • Writes the backend's check of the bearer, as Tell which user sent a request shows.
  • Declares native clients in the manifest's realm.clients, with a list for each environment. Uses configure_app_sign_in for the alternative that keeps a list outside the manifest, or for minimum versions and update URLs.
  • Calls read_app_sign_in to confirm the declared clients and the session lengths, and raises session_cap_days where you ask for longer sessions.
  • Where the app signs in through Apple's or Google's own software development kit (SDK), declares the audiences given in those tokens and writes the exchange of step 10.
  • Asks you for the app's identifier, its redirect scheme, and its app signing identities where the prompt does not mention them, and reports every value it declared.

What you need #

  • Your app's identifier in reverse-domain form, such as com.example.app, and a development build of your app ready to test with.

Before your AI starts #

For the AI tool: Check the following before starting.

  • A connected, signed-in AI tool (Connect your AI assistant).
  • An application whose manifest declares the accounts service, submitted, so each environment has a realm (Manage end users).
  • The sign-in methods your users sign in with, enabled on the realm. The emailed code and passkeys work inside the browser sheet as they do on the web.

Steps #

1. Declare the client on each environment's realm #

A native app is a public client with a client_id and redirect URIs. It has no client secret. Use the manifest's realm.clients to declare which native apps can sign in. It takes a production list, a development list, or both. Call submit_manifest with the whole manifest.

Use configure_app_sign_in to change the client list only where the manifest omits that environment's list. While the manifest lists the clients, configure_app_sign_in cannot add, remove, or change them except for minimum_version and update_url. The call refuses other changes with manifest_owned_field.

A new application has production alone. Add realm.clients.production to your application's existing manifest and submit the whole document, keeping its other services, settings, egress rules and package entries. The example below shows a minimal application; do not replace an existing manifest with it.

{
  "manifest_version": 1,
  "services": [{ "kind": "accounts" }],
  "health": "/health",
  "region": "usa",
  "egress": [],
  "audience": { "kind": "public" },
  "packages": [],
  "realm": {
    "clients": {
      "production": [
        { "client_id": "com.example.app", "redirect_uris": ["com.example.app:/callback"] }
      ]
    }
  }
}

With one environment, declare both the debug and store builds under realm.clients.production. When you turn development on, move the debug build's declaration to realm.clients.development, point that build at the development hostname, and keep the store build's required declarations in production. Each listed environment's clients are replaced on every submission. A development list on an application without development is checked at submission and declared when create_environment adds that environment.

Each list names one to ten clients. Resubmitting the manifest preserves each retained client's minimum_version and update_url. A new or copied application's clients start with those values unset.

Each entry has a unique client_id. If debug and store builds share an identifier on the same realm, use one entry with both builds' redirect URIs and Android signing fingerprints. A debug build with its own identifier has its own entry. read_app_sign_in returns the clients and never a secret.

When the two builds share an identifier and the debug build moves to development, keep the production entry with every redirect URI and signing identity the store build uses. Add an entry with the same client_id under realm.clients.development, with the debug build's redirect URIs and signing identities. Remove from the production entry only the URIs and identities the store build does not need.

If the debug and store builds share both client_id and redirect URI, a debug build pointed at production can still sign in there. To keep debug sign-ins off production, give the debug build its own redirect URI or client_id, declared on development alone.

An installed debug copy still using production can refresh there while the shared client stays declared, until its session ends. A new sign-in using a redirect URI removed from production is refused. Rebuild and install the debug build against <label>-dev.ai.host, and sign in there. If the debug build has its own identifier, move its installed copies before removing that client's production entry.

If you manage clients outside the manifest, omit that environment's list from realm.clients and use configure_app_sign_in instead. For production, the equivalent call is:

{
  "application": "<application id>",
  "environment": "production",
  "clients": [
    { "client_id": "com.example.app", "redirect_uris": ["com.example.app:/callback"] }
  ]
}

With development on, the separate-call approach takes one call per environment. Each clients array replaces that realm's list.

A client the list no longer names is removed at the next submission. Its installed apps can then neither sign in nor refresh, though a session already open keeps working until it expires. So review a change to the list as you review the code.

If the manifest lists an environment's clients, it controls that list only in that environment. There, a configure_app_sign_in call sends every listed client with the members the manifest gives it, in any order, and changes only minimum_version and update_url. Send each client's current minimum_version and update_url too, as read_app_sign_in returns them: a client the call lists without them loses them. Any other change is refused manifest_owned_field. Removing the list from the manifest leaves the clients declared, and configure_app_sign_in can change them again.

A re-created or copied application has new hostnames. So its https redirect URIs name its own hostnames, or its first submission is refused whole and records nothing. A copy made for another app also replaces client_id, ios, android, and google_client_ids with that app's own.

A redirect URI takes one of three forms, and any other is refused invalid_redirect_uri:

  • a custom scheme in reverse-domain form, such as com.example.app:/callback;
  • an https URI on one of the application's own hostnames;
  • a loopback URI, http on localhost, [::1], or an address in 127.0.0.0/8.

In the manifest, a URI outside these forms refuses the submission manifest_invalid, naming invalid_redirect_uri at the client's redirect_uris member. On the production realm, an https URI on the application's own domain passes too, through configure_app_sign_in once the domain is attached (Attach your own domain). In the manifest, such a URI passes while the same manifest declares that domain. A submission that removes the domain and keeps the URI is refused and records nothing.

The authorization endpoint matches a presented URI against a declared one exactly, except that a declared loopback URI's port may differ. The token endpoint takes the URI the sign-in returned to. Expo Go's exp:// redirect is outside the rule, so test the sign-in in a development build with your own scheme.

Each client may also carry ios (bundle_id and team_id), android (package and sha256_cert_fingerprints), and google_client_ids. Declare them for passkeys, for https redirect URIs, and for the token exchange of step 10. Once a client of a platform is declared, the platform serves these files on each environment's hostname, as JSON with a one-hour cache and no session:

Path What it lists
/.well-known/apple-app-site-association Each iOS client's application identifier, for passkeys and for https redirect URIs on that hostname.
/.well-known/assetlinks.json Each Android client's package and signing fingerprints.
/.well-known/oauth-authorization-server The realm's endpoints, for a library that reads that path.

Until then, each path stays your application's own.

On an application with one environment, choose how to declare the debug build on the production realm:

  • With its app signing identity, such as its debug signing fingerprint. The debug build then keeps passkeys and the token exchange of step 10, and the production hostname's well-known files list the debug build beside the store build.
  • With a loopback or custom-scheme redirect URI alone. The debug build then signs in through the browser redirect, with no passkeys and no exchange of Apple's or Google's own token.

Testers who sign in from a debug build are real users of the production realm, beside your live users.

2. Add the sign-in module #

The realm's endpoints sit under the reserved prefix /__account/ on the environment's own hostname. The table is the reference for what the app sends each one, and the steps below explain each:

Endpoint Address What the app sends
Authorization https://<hostname>/__account/oauth/authorize Opened in the browser sheet with response_type=code, client_id, one declared redirect_uri, code_challenge, code_challenge_method=S256, and state (step 3).
Token https://<hostname>/__account/oauth/token A form-encoded POST: grant_type=authorization_code with client_id, code, redirect_uri, and code_verifier (step 3), or grant_type=refresh_token with client_id and refresh_token (step 4), or grant_type=urn:ietf:params:oauth:grant-type:token-exchange with client_id, subject_token, and subject_token_type (step 10).
Revocation https://<hostname>/__account/oauth/revoke A form-encoded POST of the refresh credential as token, with client_id, to sign out (step 5).

A sign-in, a refresh, or a token exchange answers JSON with token_type, access_token, expires_in, refresh_token, and session_expires_at, which step 3 describes. The re-authentication of step 6 answers other members.

On an application with one environment, both builds use the production hostname, <label>.ai.host. With two, the development hostname has -dev after the application's label: the debug build uses that hostname, and the store build the production hostname. The flow is the standard one: authorization code with Proof Key for Code Exchange (PKCE) under the S256 method, the sign-in in the system browser sheet, and no client secret.

Collect the settings for each build #

Collect these values in one summary for each build, using the environment that build calls. For an existing application, call read_status and read_app_sign_in. After a successful submit_manifest, reuse its returned hostnames and realm.entra_callback where present, and any client definition in that manifest, instead of reading those values again.

The values the app needs, and where you read each:

  • Hostname: application.hostname in read_status, called with the environment the build uses.
  • Endpoints: the three in the table above, on that hostname.
  • Client id: the client's client_id under realm.clients in read_app_sign_in, called with the environment the build uses.
  • Redirect: one of that client's redirect_uris, in the same answer.
  • Headers: Authorization: Bearer <access_token> and x-turnzero-cloud-client: <client_id>/<app version> on each backend call (step 5; Keep installed clients compatible). The token and revocation endpoints take content-type: application/x-www-form-urlencoded.
  • Microsoft registration callback, for work-account sign-in: callbacks.entra in read_app_sign_in. It is on the platform's own origin, never the app's hostname (Add work-account sign-in).

Add the module to your app #

Filled in for one build, those values are the arguments the module below takes. Each placeholder is replaced with what the comment beside it names, and the last four are the app's own functions:

// The values for one build, read with the environment that build uses.
const signIn = createSignIn({
  hostname: '<label>.ai.host', // read_status: application.hostname; a debug build on a development environment uses '<label>-dev.ai.host'
  clientId: '<client_id>', // read_app_sign_in: the client's client_id under realm.clients
  redirectUri: '<redirect_uri>', // read_app_sign_in: one of that client's redirect_uris
  appVersion: '<app version>', // the build's own version, sent in x-turnzero-cloud-client
  openSignIn, // the app's browser sheet
  store, // the app's secure store
  randomBytes, // the app's random bytes
  sha256, // the app's SHA-256
});
// The module builds the three endpoints from the hostname: https://<hostname>/__account/oauth/authorize, /token, and /revoke.

This module holds the whole flow: the sign-in in the browser sheet, the code exchange, the stored pair of session token and refresh credential, and one refresh at a time. It sends the bearer and the client-version header on each backend call, and signs out. It imports nothing; the app passes its browser sheet, secure store, random bytes, and SHA-256. A test runs this module against the platform's realm and a backend that verifies the bearer.

// turnzero_sign_in.js: signs the app's users in to the realm and calls the backend with the bearer.
// It imports nothing: the app passes its browser sheet, secure store, random bytes, and SHA-256.
const SESSION_KEY = 'turnzero.session';

export function createSignIn(app) {
  const { hostname, clientId, redirectUri, appVersion, openSignIn, store, randomBytes, sha256 } = app;
  const send = app.fetch ?? globalThis.fetch;
  const origin = `https://${hostname}`;
  const base64url = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  const form = (fields) => new URLSearchParams(fields).toString();
  const headers = { accept: 'application/json', 'x-turnzero-cloud-client': `${clientId}/${appVersion}` };
  const held = async () => JSON.parse((await store.get(SESSION_KEY)) ?? 'null');

  // Posts to the token endpoint and keeps the pair it returns.
  async function token(fields) {
    const answer = await send(`${origin}/__account/oauth/token`, {
      method: 'POST',
      headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' },
      body: form({ ...fields, client_id: clientId }),
    });
    const body = await answer.json();
    if (answer.status !== 200) {
      await store.delete(SESSION_KEY);
      throw new Error(`sign in again: ${body.error}`);
    }
    const session = { accessToken: body.access_token, refreshToken: body.refresh_token, expiresAt: Date.now() + body.expires_in * 1000 };
    await store.set(SESSION_KEY, JSON.stringify(session));
    return session;
  }

  // Opens the realm's sign-in page in the browser sheet and exchanges the code. Null where the person closed the sheet.
  async function signIn() {
    const verifier = base64url(randomBytes(32));
    const state = base64url(randomBytes(16));
    const challenge = base64url(await sha256(verifier));
    const query = form({ response_type: 'code', client_id: clientId, redirect_uri: redirectUri, code_challenge: challenge, code_challenge_method: 'S256', state });
    const returned = await openSignIn(`${origin}/__account/oauth/authorize?${query}`, redirectUri);
    if (returned === null) return null;
    const params = new URLSearchParams(returned.slice(returned.indexOf('?') + 1));
    if (params.get('state') !== state || !params.get('code')) throw new Error('the sign-in returned no code for this request');
    return token({ grant_type: 'authorization_code', code: params.get('code'), redirect_uri: redirectUri, code_verifier: verifier });
  }

  // One refresh at a time: each refresh replaces the refresh credential.
  let refreshing = null;
  function refresh() {
    refreshing ??= (async () => {
      const session = await held();
      if (!session) throw new Error('sign in again: no session');
      return token({ grant_type: 'refresh_token', refresh_token: session.refreshToken });
    })().finally(() => {
      refreshing = null;
    });
    return refreshing;
  }

  // Calls the backend with the bearer, refreshing before the hour passes and once more after a 401.
  async function call(path, init = {}) {
    let session = await held();
    if (!session) throw new Error('sign in again: no session');
    if (session.expiresAt - 60_000 <= Date.now()) session = await refresh();
    const request = (bearer) => send(`${origin}${path}`, { method: 'GET', ...init, headers: { ...headers, ...init.headers, authorization: `Bearer ${bearer}` } });
    const answer = await request(session.accessToken);
    return answer.status === 401 ? request((await refresh()).accessToken) : answer;
  }

  // Ends the session on the realm and forgets it on the device, even offline.
  async function signOut() {
    const session = await held();
    await store.delete(SESSION_KEY);
    if (!session) return;
    await send(`${origin}/__account/oauth/revoke`, {
      method: 'POST',
      headers: { ...headers, 'content-type': 'application/x-www-form-urlencoded' },
      body: form({ token: session.refreshToken, client_id: clientId }),
    }).catch(() => {});
  }

  return { signIn, refresh, call, signOut };
}

In an Expo development build, the wiring is one more file, the one place the app names Expo. It needs expo-web-browser, expo-secure-store, and expo-crypto.

// turnzero.js: the sign-in module's seams in their Expo forms.
import * as Crypto from 'expo-crypto';
import * as SecureStore from 'expo-secure-store';
import * as WebBrowser from 'expo-web-browser';
import { createSignIn } from './turnzero_sign_in';

WebBrowser.maybeCompleteAuthSession();

export const turnzero = createSignIn({
  hostname: 'shop.ai.host',
  clientId: 'com.example.app',
  redirectUri: 'com.example.app:/callback',
  appVersion: '1.0.0',
  openSignIn: async (url, redirectUri) => {
    const result = await WebBrowser.openAuthSessionAsync(url, redirectUri);
    return result.type === 'success' ? result.url : null;
  },
  store: { get: SecureStore.getItemAsync, set: SecureStore.setItemAsync, delete: SecureStore.deleteItemAsync },
  randomBytes: (count) => Crypto.getRandomBytes(count),
  sha256: async (text) => new Uint8Array(await Crypto.digest(Crypto.CryptoDigestAlgorithm.SHA256, new TextEncoder().encode(text))),
});

The app calls turnzero.signIn() from its sign-in button, turnzero.call('/api/notes') for each backend request, and turnzero.signOut() to sign out. A library of your own works too. Expo AuthSession's useAutoDiscovery and AppAuth's fetchFromIssuer read the OpenID Connect discovery path, which the platform does not serve: a request for it under /__account/ returns 404 not_found, whose detail names /.well-known/oauth-authorization-server. Give either library the endpoints in the table instead.

3. Run the sign-in and exchange the code #

The sign-in opens the authorization endpoint with response_type=code, the client_id, one declared redirect_uri, the code_challenge under code_challenge_method=S256, and a state. The realm shows its sign-in page in the browser sheet. When the person signs in, the sheet returns to the redirect URI with a code and the state, and no session is opened in the browser. The code is valid for sixty seconds and is used once.

The exchange posts to the token endpoint, form-encoded, with grant_type=authorization_code, client_id, code, redirect_uri, and code_verifier. It opens the session and returns JSON:

Member What it holds
token_type bearer.
access_token The session token, sent as the bearer. It lasts one hour.
expires_in The token's remaining life in seconds, 3600 on a new token.
refresh_token The refresh credential, replaced at each refresh.
session_expires_at When the session itself ends, unless a refresh extends it.

Keep both values in the device's secure store, as the module's store does. A spent or expired code, a code issued to another client, a redirect URI other than the code's, and a verifier that fails its challenge are each refused invalid_grant. The app then starts the sign-in again.

4. Refresh the session #

Before the hour passes, the app posts grant_type=refresh_token, client_id, and refresh_token to the token endpoint. The response has the members step 3 lists: a fresh token and a fresh refresh credential, and the presented credential is replaced. Each refresh extends the session by the realm's session_days, up to session_cap_days from the sign-in: 30 days and 365 days by default. At the cap the session expires, and the app signs in again.

Replace the stored credential with each response, and keep one refresh in flight at a time, as the module does. If a response is lost, a retry with the same credential within sixty seconds returns a fresh pair, because a lost response is not a sign of theft. If a second refresh starts with the newer credential before the first has its response, one of the two is refused, and the app signs in again. Reusing a replaced credential after sixty seconds is refused refresh_reused, and signs the user out on every device that had it.

5. Call the backend with the bearer #

Send the token as Authorization: Bearer <token> on every request to your backend, as the module's call does. The serving router treats a bearer of that form as it treats the session cookie a browser holds, __Host-turnzero_cloud_realm, whose value is a token of the same form. It verifies the bearer and forwards the request with the session header set. Under an invited or workforce audience, the bearer passes the audience check as the cookie does. Your backend tells which user sent the request as Tell which user sent a request shows, its sample reading the bearer and the cookie alike.

See Raise the minimum version for when to show the update screen and how to set store links for iOS and Android.

The realm's own routes accept the bearer too: GET /__account/me returns the signed-in user, and the passkey and sign-out routes take it. The accounts service's verification route accepts it from your backend as it accepts the cookie's token.

A bearer the router cannot verify is refused 401 authentication_required with WWW-Authenticate: Bearer error="invalid_token" before it reaches your backend, on every audience. The router never renews a bearer, so refresh before the hour passes, and sign in again on a 401 that follows a refresh.

Public or workforce for a backend that verifies the bearer #

Under a public audience, a request with no bearer reaches your backend, which refuses it itself. Under workforce, the router refuses it first with 401, and sends a GET that accepts text/html to the sign-in page. The realm then signs people in with the declared tenant's entra route alone (Add work-account sign-in). So a backend whose only sign-in method is one company's work account declares workforce. A backend that also offers Google, GitHub, Apple, or the emailed code declares public. Under workforce, a provider's callback path goes in session_free_paths (Choose who may sign up).

Under invited or workforce, no client's request without a live session reaches your code outside your session_free_paths, so the platform never shows your own 401 branch there. The router's refusal says so: its detail opens by naming the serving router. Exercise your own 401 and 503 branches where the serving router does not run: the offline tests on the Account double, or the run line on your machine. Test your application locally and Test a local run show each. Under workforce, hand the local run the token a tenant user's or a test end user's sign-in gave your app.

To sign out, post the refresh credential as token to the revocation endpoint with the client_id, as the module's signOut does, or post to /__account/signout with the bearer. Either ends the session and its refresh credential at once, and every router refuses the token within sixty seconds (the copy interval). A sign-out made offline clears the app's own store and leaves the session open on the realm until the user ends it from the session list.

6. Confirm it is you, from the app #

Deleting the account and some passkey actions need a fresh sign-in, not the existing session. From the app, run the authorization again with prompt=login. The sign-in page opens as before, and the person signs in with the account they already have.

Exchange the code as in step 3, and send the app's current token as the bearer with the exchange. The exchange marks that session as freshly authenticated for five minutes and opens no new session.

{ "contract_version": 1, "reauthenticated": true, "until": "2026-09-27T00:05:00.000Z" }

An exchange without the bearer, or with another user's, is refused reauthentication_other_account. So is a sign-in that resolves to no existing user: the code's sign-in creates nobody.

7. Register a passkey from inside the app #

After the exchange in step 6, the app may register a passkey under the same bearer within five minutes. Post to /__account/passkeys/register/options and then to /__account/passkeys/register with the platform's credential response, as the web page does. Only a user who signs in by emailed code can register one, and for any other user both routes return 409 passkey_requires_email. Passkeys for your users covers the routes.

The passkey ceremony, the exchange that creates or uses a passkey, binds the passkey to the environment's hostname, so it also works on the sign-in page in the browser sheet. Two things let the app run it. On iOS, the app declares the associated domain webcredentials:<hostname> in its entitlements, and the app-site association file the platform serves lists the app. On Android, the realm's declared signing fingerprints become accepted origins for the ceremony, and the asset links file includes the get_login_creds relation. A registration from an app the realm does not declare is refused passkey_origin_mismatch.

8. Show the user's sessions and end one #

GET /__account/sessions with the bearer lists the user's live sessions, in the app and in a browser alike, newest first, at most 100, and total counts them all. A user has at most 100 live sessions: the sign-in that would open the 101st ends the oldest. Each entry gives the session's id and kind, its client_id where native, and when it was created, last_used, and expires. The presenting session is marked current. No entry contains a token or a refresh credential.

{
  "contract_version": 1,
  "sessions": [
    { "id": "<session id>", "kind": "native", "client_id": "com.example.app", "created": "2026-09-27T00:00:00.000Z", "last_used": "2026-09-27T09:00:00.000Z", "expires": "2026-10-27T09:00:00.000Z", "current": true },
    { "id": "<session id>", "kind": "browser", "client_id": null, "created": "2026-09-20T00:00:00.000Z", "last_used": "2026-09-26T21:00:00.000Z", "expires": "2026-10-20T00:00:00.000Z", "current": false }
  ],
  "total": 2
}

A native session's last_used moves with each refresh. A browser session's last_used moves with each hourly re-issue of its token, made at the user's first request after the token's hour.

To end one, post to /__account/sessions/<id>/revoke with the bearer. The session ends at once, the current one included, and every router refuses its token within sixty seconds. An id that matches no live session of this user is refused not_found, and nothing ends. A web page that posts with the session cookie is accepted only from the application's own origin.

9. Delete the account from the app #

Deletion needs the fresh sign-in of step 6 on the session that deletes. Within five minutes of that exchange, post to /__account/delete with the same bearer. Without it the post is refused fresh_authentication_required, and the app runs step 6 first.

The response gives counts of what was removed. Every session of the user ends at once on every device, in the app and in a browser, and each refresh credential with it. Clear the stored pair, and return the app to its signed-out state.

10. Sign in with Apple's or Google's own SDK #

An app may sign in through the operating system's own sheet instead of the browser sheet. Apple's AuthenticationServices returns an Apple ID token, and Google's sign-in SDK returns a Google ID token. The token endpoint exchanges either for the same session step 3 opens.

The realm needs three things first:

  • the route of the token's issuer among the realm's sign_in_methods, apple or google;
  • the audience given in the token, declared on the client: ios.bundle_id for an Apple token, and one of google_client_ids for a Google token;
  • for the apple route, the realm's apple member, which Add Sign in with Apple describes.

Post the token to the token endpoint, form-encoded.

grant_type=urn:ietf:params:oauth:grant-type:token-exchange
client_id=com.example.app
subject_token=<the ID token>
subject_token_type=urn:ietf:params:oauth:token-type:id_token

The response is the one step 3 shows, with the same refresh. The platform verifies the token against its issuer's published keys and checks its expiry and its audience. The person's account is found or created as a sign-in in the browser sheet finds or creates it.

On an invitation-only realm the exchange creates no account and is refused unrecognized_invitation, since it includes no invitation. The person redeems their invitation in the browser sheet first, and the exchange then finds the account.

An exchange whose address another account of the app already has is refused identity_collision. The person then signs in through the browser sheet with that account's own route, and links the two there.

Register the platform's sender with Apple's private email relay, as Add Sign in with Apple says, or a user who hides their address receives no code and no notice.

From a desktop app #

A macOS or Windows app is a native client like any other. It is declared on the realm in the manifest's realm member or with configure_app_sign_in, signs in through the system browser, and exchanges the code as steps 1 to 5 describe. Never run the sign-in in a web view embedded in the app: Google refuses its sign-in there.

Its redirect URI is a loopback URI in the form step 1 states, or a custom scheme. A loopback redirect is matched on any port, so a desktop app may bind a free port at each sign-in. The scheme, the host, the path, and the query still match the declared URI exactly.

The ios, android, and google_client_ids members do not apply to a desktop app. Universal links, app links, and the well-known files of step 1 are not used in its sign-in. The version header and the minimum version apply as on a phone (Keep installed clients compatible).

Push reaches a macOS app only where it registers the platform ios with a token issued under the one bundle identifier set with configure_push, the iOS app's. A desktop app with an identifier of its own gets no push, and no Windows app does (Send push notifications).

Where the app keeps its refresh credential is the app's choice. The operating system's keychain is the secure form, and a plain file is not.

Expected result #

read_app_sign_in on each environment returns the app under clients, with its redirect URIs and identities and no secret. In a development build the sign-in opens in the browser sheet, returns to the app with a code, and the exchange returns a bearer the backend accepts.

An hour later the refresh returns a fresh pair, and session_expires_at moves forward. Reusing a replaced refresh credential after the sixty-second retry window ends the session, and the app signs in again. The relevant well-known files are available for each declared platform. With the required app identities and passkey configuration, a passkey registered in the app also works on the web.

GET /__account/sessions lists the app's session beside any browser session, and ending one from the list signs that device out. A native session deletes its account after the fresh sign-in of step 6. An Apple or Google ID token from the platform's own SDK exchanges for the same session.

Refusals #

See the refusals reference for other platform errors.

Refusal Status Cause Remedy
invalid_client 400 The client_id matches no client the realm declares. Read read_app_sign_in on the environment whose hostname the build calls, the -dev one for development, and check the client_id is among its clients. On one environment, the client goes under production, since a development list waits for create_environment. Declare it in the manifest's clients list for that environment and submit the manifest, or with configure_app_sign_in where the manifest lists none.
manifest_owned_field 409 A configure_app_sign_in call would add, remove, or change a client the manifest lists for this environment, beyond its minimum_version and update_url. Change the list in the manifest and submit it again, or remove the list (Configure the realm). To change only minimum_version or update_url, send each listed client's other members as the manifest lists them; the detail names each client that differs.
invalid_redirect_uri 400 The redirect URI is outside the three forms, or the client does not declare it. Declare the URI in one of the three forms and present it exactly; only the port may differ from a declared loopback URI.
invalid_request 400 The authorization request lacks the S256 challenge or the state, or the token request asks for another grant. A request containing a NUL character (U+0000) or an unpaired UTF-16 surrogate is refused too, and its error_description identifies the character rather than a member. Send response_type=code, a code_challenge under S256, and a state; use the three grants. Remove a character the error_description identifies.
invalid_grant 400 The code or the refresh credential is spent, expired, unknown, or not this client's, or the verifier fails. An ID token of step 10 is exchanged once, and a second exchange of it is refused. Sign in again from the app.
refresh_reused 400 A replaced refresh credential was presented after sixty seconds, and the session is ended. Sign in again, and replace the stored credential with each response.
authentication_required 401 The bearer sent to the backend is expired, ended, or another realm's, and the router refused it. Refresh at the token endpoint, and sign in again where the refresh is refused.
not_found 404 The session id matches no live session of this user, or no route under /__account/ serves the path or the method, such as the OpenID Connect discovery path. Read the list again, and use an id it returns. For a path, use the endpoints in step 2.
user_suspended 403 The user is suspended in this realm. Reinstate the user by calling set_end_user_standing with standing: active.
fresh_authentication_required 403 The deletion was posted without a fresh sign-in on this session within five minutes. Run step 6 with this session's token as the bearer, then post the deletion again.
reauthentication_other_account 403 The re-authentication exchange had no bearer, another user's bearer, or a sign-in that resolves to no user. Send the app's current token as the bearer, and sign in with the account the app is signed in with.
id_token_invalid 400 The ID token of step 10 failed verification: its signature, issuer, expiry, or audience. Sign in again in the app, and declare the token's audience on the client.
provider_not_enabled 400 The ID token's issuer is Apple or Google, and the realm's sign-in methods lack apple or google. Add the route to the realm's sign_in_methods in the manifest's realm member and submit it, or with configure_app_sign_in where the member names no sign_in_methods.
identity_collision 409 The ID token's address belongs to another account of the app. Sign in through the browser sheet with that account's route, and link the two there.
passkey_origin_mismatch 400 The passkey ceremony ran from an app the realm does not declare, or an Android build signed with an undeclared certificate. Declare the app signing identity on the realm, with every signing fingerprint.