Skip to Content
Otoko Identity

Mobile apps

A phone app signs in through your backend, with no browser pages.

Mobile app through your backend

A mobile app has no browser pages: your backend signs people in and out for it, so it needs an app with a backend. Connect an app offers Mobile app only then. The mobile Quickstart builds one from start to finish.

Agent prompt

Paste this into your coding agent, in your mobile app's and backend's project. It tells you what to register on the console, then writes sign-in, sign-up, forgot password, refresh and sign-out through your backend, the routes Otoko Identity calls, and the token check.

Show the full prompt

Connect this mobile app's sign-in to Otoko Identity, through its backend

You are connecting the sign-in of the mobile app you're working in to Otoko Identity (OI). A mobile app has no browser pages and needs no OI library: it signs people in on its own screens and talks only to its own backend, and the backend calls OI's API with the app's API key, which never leaves the server. The backend gives the app an access token and a refresh token, checks the access token on every API call, and is also the backend OI calls: on every sign-in, when a session ends, and when an account is made. Work through the steps below in order, and stop where a step says to wait for the person.

Scope

  • The backend: sign-in, refresh and sign-out; sign-up with a code OI emails; forgot password; a protected GET /api/me that makes the person's user on their first request; and the three routes OI calls, /internal/v1/sign-in-check, /internal/v1/session-ends and the signed /internal/v1/account-created.
  • The app: sign-in, sign-up, code and forgot-password screens, and a home screen that calls the API and signs out, with the tokens in the phone's secure storage.
  • Change nothing unrelated to signing in.

Rules

  • The API key, the webhook secret and the signing secret live only in the backend's env file, which git ignores.
    • Never open, print or paste the whole env file, and never ask for a secret in the chat. To check a setting is there, look for its name only (for example grep -c '^IDENTITY_API_KEY=' .env).
    • Never put a secret in the mobile app (anyone can unpack an app and read it), a log line or a commit. The app holds only the backend's address.
  • Never send a person's password anywhere but the backend's own routes, and never log it.
  • The app keeps the tokens in the platform's secure storage (the Keychain on iOS, the Keystore on Android: expo-secure-store, flutter_secure_storage), never in AsyncStorage or plain preferences.
  • For the backend's token checks, use a maintained JWT library, such as jose for Node or PyJWT for Python. Never write them by hand.
  • Use https everywhere outside a local machine.

1. Look at the project

  • Find the app's stack (React Native with Expo and Flutter are the worked examples; Swift, Kotlin or Ionic take the same steps), its backend's (Express, Next.js route handlers and FastAPI are the worked examples), the backend's port (the examples use 3001), how the app calls it, and any sign-in either already has. If the backend isn't in this project, ask where it is.
  • Confirm with the person that it's a mobile app that signs in through its backend. If it's a web app, stop and send the person to https://identity-docs.otoko.com/quickstarts.

2. Tell the person what to register, then wait

The app is registered on OI's console; you can't do this part.

  1. Name the backend's env file: .env, or .env.local for Next.js. Check that git ignores it before anything is pasted, and add it to .gitignore if not.
  2. Tell the person to open https://identity.otoko.com/admin/apps/new and:
    • Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer Yes: a mobile app signs in through its backend.
    • How people sign in: choose Mobile app. It has no app address and no return addresses. Keep the Client ID it suggests.
    • Backend and email: type the Backend address, where OI reaches the backend. With OI running in Docker on the same machine, that's http://host.docker.internal:3001, not localhost. Leave Send this app's emails through Otoko Identity's mail server ticked, unless the app has its own mail server: then they untick it, type the From address, and fill in the Mail server section that appears: host, port, encryption, username and password. The person types the password there themselves; never ask for it in the chat.
    • Choose Create, then on Connect your app the Backend section's Copy all, and paste it into the backend's env file. The API key and the webhook secret are shown only now. The Mobile app section holds only the client ID, already in IDENTITY_ALLOWED_CLIENT_IDS: the mobile app gets none of the values.
    • Check the Login settings: on the app's Overview tab, keep Verify email for new accounts and Forgot password on. A mobile client has no Allow sign-up: the backend makes the accounts with the API key.
    • Make the signing secret: on the Security tab, under Webhook signing secret, choose Make signing secret, and paste the whsec_… value into the env file as IDENTITY_WEBHOOK_SIGNING_SECRET. It's shown once.
  3. Ask them to tell you when it's done, and wait. Then check the paste by names only.

From then on, OI asks the backend on every sign-in: until it runs and answers /internal/v1/sign-in-check, nobody can sign in.

3. Settings

  • The backend: IDENTITY_URL, IDENTITY_API_KEY, IDENTITY_ALLOWED_CLIENT_IDS (the mobile client's ID), IDENTITY_CALLBACK_TOKEN (the webhook secret) and IDENTITY_WEBHOOK_SIGNING_SECRET (empty until the app has one), plus PORT=3001. Add an .env.example with the same names and placeholder values.
  • The app: only the backend's address. React Native: EXPO_PUBLIC_BACKEND_URL in .env. Flutter: --dart-define=BACKEND_URL=…, read in lib/api/backend.dart, with http://localhost:3001 when none is given. On the Android emulator, the computer is 10.0.2.2.

4. Install

  • Backend: Express express jose (dev: typescript tsx @types/express @types/node); Next.js jose; FastAPI fastapi, uvicorn[standard], pyjwt[crypto]>=2.14, httpx and python-dotenv.
  • App: React Native npx expo install expo-secure-store; Flutter flutter pub add http flutter_secure_storage.

5. The backend: the routes the app calls

One helper calls IDENTITY_URL followed by /internal/v1 with Authorization: Bearer <IDENTITY_API_KEY> and a JSON body, reading the answer as JSON only when it is JSON. A call that sends an email or makes an account also sends an Idempotency-Key, a new random UUID (reuse it if you add retries). Each route passes the person's IP address as client_ip where shown, so OI's limits fall on that person, not on the server. When OI refuses, the route answers with OI's status and {"error": <OI's key>, "retry_after_seconds": ...}, so the app can say what went wrong.

  • POST /mobile/sign-in {email, password}: calls POST /internal/v1/sessions/password with {"email", "password", "client_ip"}. OI checks the password and asks the sign-in check. A 200 answers the app {access_token, refresh_token, expires_in}.
  • POST /mobile/refresh {refresh_token}: calls POST /internal/v1/sessions/refreshes, and answers the new pair. The refresh token rotates: the old one stops working. 400 invalid_grant means the session is over.
  • POST /mobile/sign-out {refresh_token}: calls POST /internal/v1/sessions/sign-outs, which answers 204. OI then calls session-ends.
  • POST /mobile/sign-up {email, password, first_name, last_name, language}: calls POST /internal/v1/identities with those and "email_verified": false. On 201, calls POST /internal/v1/identities/{id}/code with {language}, and answers 202 even if that email failed (log it). 409 conflict means the email already has an account.
  • Finding an account by email, for the next three: GET /internal/v1/identities?email=…. A 404 or 422 means none; any other non-200 is a refusal to pass on.
  • POST /mobile/sign-up/code {email, language}: if there's an account, calls …/identities/{id}/code without waiting for it, logging a failure. Answers 202 either way.
  • POST /mobile/sign-up/verify {email, code}: with an account, calls …/identities/{id}/code-checks with {code, client_ip}, and answers 204, or OI's 400 invalid_code or 429. With none, calls POST /internal/v1/unknown-addresses/code-failures with {email, client_ip}, passes on a 429, and otherwise answers 400 invalid_code, the same as a wrong code.
  • POST /mobile/forgot-password {email}: if there's an account, calls …/identities/{id}/password-email with {"purpose": "reset"} without waiting for it. Answers 202 either way. OI emails a link to its own set-password page.

The answers the app must handle:

  • 401 invalid_credentials: a wrong email or password, and also an email not verified yet. Say so without saying which, and offer to enter the code.
  • 403 wrong_application: the sign-in check said no. 403 account_setup_incomplete: the person has a step still to do; show the app's own screen for it.
  • 429 rate_limited: pass on the wait, from retry_after_seconds.
  • 503 unavailable: OI couldn't ask the backend; try again later.
  • From sign-up: 409 conflict, password_too_short, password_compromised, and 503 mail_server_not_set_up.

Passkeys (optional, only if the person asks): POST /internal/v1/sessions/passkey-challenges gives WebAuthn's options and a challenge_token, good once for five minutes. The device's answer goes to POST /internal/v1/sessions/passkey-assertions with that token, and signs in like a password.

6. The backend: the token check and /api/me

Every route that needs a signed-in person checks the bearer access token, and answers 401 with WWW-Authenticate: Bearer to a missing or failing one:

  • ES256 only, with keys from IDENTITY_URL followed by /.well-known/jwks.json, cached by the library, and iss equal to IDENTITY_URL.
  • aud and azp both among IDENTITY_ALLOWED_CLIENT_IDS.
  • The typ claim in the token's payload is Bearer. It's a claim, not the JWT header's typ: with jose, check it among the claims, not with the typ option.
  • sub, exp, iat, jti and sid all present. Refuse a token with "service": true, and one whose sid is among the ended sessions.
  • When OI's keys can't be fetched at all (not a token naming an unknown key), answer 503 {"error": "unavailable"}: the token may be fine.

GET /api/me: look the user up by sub. If there's none, call IDENTITY_URL followed by /oauth/userinfo with the same access token, which answers sub, email and locale for these tokens, and upsert the user keyed by sub, never by email. A 401 from userinfo answers 401; userinfo unreachable or failing answers 503. Answer {"sub", "email", "client": <azp>, "locale"}. The API needs no CORS: the app isn't a browser.

7. The backend: the routes OI calls

Under /internal/v1. Each first checks Authorization: Bearer <IDENTITY_CALLBACK_TOKEN> in constant time, and answers 401 to anything else, or to every call when the setting is unset.

POST /internal/v1/sign-in-check
Authorization: Bearer <IDENTITY_CALLBACK_TOKEN>
Content-Type: application/json

{ "sub": "5b1c6f0e-0000-4000-8000-000000000000", "client_id": "your-client-id", "pending_actions": [] }

HTTP/1.1 200 OK
Content-Type: application/json

{ "allowed": true }
  • sign-in-check: log [sign-in-check] <sub> on <client_id>: allowed and answer {"allowed": true}. Leave a comment that a real app checks its own records here, such as a blocked account or an unpaid plan. Keep it read-only and fast (OI waits 3 seconds), and make no user here. Anything other than {"allowed": true} keeps the person out.
  • session-ends: the body is {"sids": [...], "sub": "..." or null, "ended_at": "..."}. Answer 400 unless sids is a list of strings. Store each sid among the ended sessions the token check reads, log [session-ends] <n> session(s), and answer 204. Without a 2xx, OI tries again for 6 hours.
  • account-created: read the raw body bytes, before any JSON parsing. Verify the Standard Webhooks signature: base64 of HMAC-SHA256 over webhook-id, a dot, webhook-timestamp, a dot, then the body. The key is IDENTITY_WEBHOOK_SIGNING_SECRET's base64-decoded bytes after whsec_; when that's empty, it's IDENTITY_CALLBACK_TOKEN's own UTF-8 bytes. webhook-signature may hold several v1, entries separated by spaces: refuse more than 10, and accept any that matches, compared in constant time. Answer 401 to a missing header, a bad signature, or a webhook-timestamp that isn't plain digits or is more than 5 minutes from the clock. Answer 204 at once to a webhook-id already stored. Otherwise parse the body, and for "type": "account.created" upsert the user from data (sub, email, first_name, last_name, language; names may be null), keyed by sub as above, store the webhook-id, and answer 204. It's never sent for accounts the backend made itself through /internal/v1/identities, so /api/me still makes those users.

OI calls these server to server, with no cookies: keep them out of the backend's sign-in middleware and CSRF protection, or every sign-in fails. The examples keep the ended sessions, the webhook ids and the users in memory; say in your report that production needs a real store.

8. The app

  • It calls only the backend, with a timeout (15 seconds), and turns a refusal into a message from its error, such as wrong email or password, too many tries with the wait, or can't reach the server.
  • Screens: sign-in (email, password, and links to Create an account and Forgot password?); sign-up (email, password, first and last name, and the email language, en or de from the phone's); the code screen (the code, and Send a new code), after sign-up or from Haven't verified your email? Enter the code under a refused sign-in; forgot password; and a home screen with Ask the API who I am (GET /api/me) and Sign out. After the code, the person signs in.
  • Tokens: saved in secure storage after sign-in, and read on start to open the home screen when someone is signed in.
  • API calls send Authorization: Bearer <access token>. On a 401, refresh once (one refresh at a time, shared by calls that all got 401, as a refresh token works only once), save the new pair, and try again. Still 401, or a 400 from refresh: delete the tokens and show sign-in. A network error or a 503: keep the tokens, and try again later.
  • Sign out deletes the tokens at once, then calls /mobile/sign-out with the refresh token without waiting. A refresh that finishes after a sign-out keeps nothing, and signs out its new refresh token too.

9. Check it works

Start the backend (npm run dev, npm run dev -- -p 3001 for Next.js, or uvicorn app.main:app --port 3001 --env-file .env).

  1. curl -i http://localhost:3001/api/me and a POST to /internal/v1/sign-in-check with no bearer token must both answer 401.
  2. Sign-up sends a real email: ask the person for the address, never invent one. A POST to /mobile/sign-up with it answers 202. They give you the emailed 8-digit code for /mobile/sign-up/verify, which answers 204, then /mobile/sign-in answers the tokens. Never print the tokens or the password in full.

Then start the app pointed at the backend (npx expo start, or flutter run --dart-define=BACKEND_URL=http://10.0.2.2:3001), and ask the person to:

  1. Choose Create an account, type the code, then sign in. The backend's log shows [sign-in-check] … allowed.
  2. Choose Ask the API who I am. The app shows their sub, the mobile client's ID and their locale.
  3. Leave the app until the access token expires (30 minutes on a new app; the client's Access token lifespan can be set to one minute to try it), then ask again. The app renews the token and the call works.
  4. Choose Sign out. The log shows [session-ends] 1 session(s).
  5. Choose Forgot password?, open the emailed link, set a new password on OI's page, and sign in with it.

If sign-in answers 503 unavailable, OI can't reach the sign-in check: check the backend address. If every call to OI answers 401 invalid_api_key, IDENTITY_API_KEY isn't the app's current key. Can't reach the server on a phone means localhost isn't the computer there. For other errors, read https://identity-docs.otoko.com/troubleshooting.

Finish with a short report: the files you changed, the routes and screens you added, the settings the code reads (by name), and anything the person still has to do.

More detail

  • Its client is of type mobile, Mobile app on the console, so it has no redirect addresses, no post-logout addresses and no Action URL. Your app talks only to your own backend, which calls Otoko Identity with the app's API key.
  • Your backend signs people in and out for it through Sessions: with a password or a passkey, then refreshes and signs out.
  • Pass the person's IP address on as client_ip: the sign-in limits count by it.
  • A person with a required action pending gets 403 account_setup_incomplete, and your app shows its own screen for it. On an app whose account flows are Identity's own, the default, a right password for an email still to verify answers 401 invalid_credentials, as a wrong one does.
  • People manage their own passkeys through /internal/v1/passkeys, with the API key and their access token in the X-Access-Token header.
  • Android passkey origins. A mobile client with passkeys on lists its own Android app's origins on its Clients tab: android:apk-key-hash: and the unpadded base64url SHA-256 of each signing certificate, debug and release, at most 10. A new mobile client with passkeys on needs at least one (422 passkey_origin_required), and only a mobile client may have them (422 invalid_passkey_origin). So its passkeys answer only to its own Android app, never to another app's.
    • One made before them may have none. It then falls back to the server's own lists, and the console flags it until it's given its own.
    • An iOS app needs none, as it reports the pages' own origin.
    • The pages' assetlinks.json still comes from the server's settings, so list each certificate there too.
  • There is no sign-in session behind it, so its refresh tokens last as long as they are set to. /oauth/userinfo answers sub, email and locale for its access tokens.