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.
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/methat makes the person's user on their first request; and the three routes OI calls,/internal/v1/sign-in-check,/internal/v1/session-endsand 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 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
- 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.
- Name the backend's env file:
.env, or.env.localfor Next.js. Check that git ignores it before anything is pasted, and add it to.gitignoreif not. - 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, notlocalhost. 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 asIDENTITY_WEBHOOK_SIGNING_SECRET. It's shown once.
- 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) andIDENTITY_WEBHOOK_SIGNING_SECRET(empty until the app has one), plusPORT=3001. Add an.env.examplewith the same names and placeholder values. - The app: only the backend's address. React Native:
EXPO_PUBLIC_BACKEND_URLin.env. Flutter:--dart-define=BACKEND_URL=…, read inlib/api/backend.dart, withhttp://localhost:3001when none is given. On the Android emulator, the computer is10.0.2.2.
4. Install
- Backend: Express
express jose(dev:typescript tsx @types/express @types/node); Next.jsjose; FastAPIfastapi,uvicorn[standard],pyjwt[crypto]>=2.14,httpxandpython-dotenv. - App: React Native
npx expo install expo-secure-store; Flutterflutter 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}: callsPOST /internal/v1/sessions/passwordwith{"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}: callsPOST /internal/v1/sessions/refreshes, and answers the new pair. The refresh token rotates: the old one stops working. 400invalid_grantmeans the session is over.POST /mobile/sign-out{refresh_token}: callsPOST /internal/v1/sessions/sign-outs, which answers 204. OI then callssession-ends.POST /mobile/sign-up{email, password, first_name, last_name, language}: callsPOST /internal/v1/identitieswith those and"email_verified": false. On 201, callsPOST /internal/v1/identities/{id}/codewith{language}, and answers 202 even if that email failed (log it). 409conflictmeans 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}/codewithout waiting for it, logging a failure. Answers 202 either way.POST /mobile/sign-up/verify{email, code}: with an account, calls…/identities/{id}/code-checkswith{code, client_ip}, and answers 204, or OI's 400invalid_codeor 429. With none, callsPOST /internal/v1/unknown-addresses/code-failureswith{email, client_ip}, passes on a 429, and otherwise answers 400invalid_code, the same as a wrong code.POST /mobile/forgot-password{email}: if there's an account, calls…/identities/{id}/password-emailwith{"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. 403account_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, fromretry_after_seconds. - 503
unavailable: OI couldn't ask the backend; try again later. - From sign-up: 409
conflict,password_too_short,password_compromised, and 503mail_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_URLfollowed by/.well-known/jwks.json, cached by the library, andissequal toIDENTITY_URL. audandazpboth amongIDENTITY_ALLOWED_CLIENT_IDS.- The
typclaim in the token's payload isBearer. It's a claim, not the JWT header'styp: with jose, check it among the claims, not with thetypoption. sub,exp,iat,jtiandsidall present. Refuse a token with"service": true, and one whosesidis 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>: allowedand 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 unlesssidsis a list of strings. Store eachsidamong 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 overwebhook-id, a dot,webhook-timestamp, a dot, then the body. The key isIDENTITY_WEBHOOK_SIGNING_SECRET's base64-decoded bytes afterwhsec_; when that's empty, it'sIDENTITY_CALLBACK_TOKEN's own UTF-8 bytes.webhook-signaturemay hold severalv1,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 awebhook-timestampthat isn't plain digits or is more than 5 minutes from the clock. Answer 204 at once to awebhook-idalready stored. Otherwise parse the body, and for"type": "account.created"upsert the user fromdata(sub,email,first_name,last_name,language; names may be null), keyed bysubas above, store thewebhook-id, and answer 204. It's never sent for accounts the backend made itself through/internal/v1/identities, so/api/mestill 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,
enordefrom 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-outwith 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).
curl -i http://localhost:3001/api/meand a POST to/internal/v1/sign-in-checkwith no bearer token must both answer 401.- Sign-up sends a real email: ask the person for the address, never invent one. A POST to
/mobile/sign-upwith it answers 202. They give you the emailed 8-digit code for/mobile/sign-up/verify, which answers 204, then/mobile/sign-inanswers 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:
- Choose Create an account, type the code, then sign in. The backend's log shows
[sign-in-check] … allowed. - Choose Ask the API who I am. The app shows their
sub, the mobile client's ID and their locale. - 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.
- Choose Sign out. The log shows
[session-ends] 1 session(s). - 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
- https://identity-docs.otoko.com/quickstarts/mobile-app: this setup, step by step, with code for each framework.
- https://identity-docs.otoko.com/app-settings/mobile-apps: the mobile client, and https://identity-docs.otoko.com/api-reference/your-backends-calls#sessions for its calls.
- https://identity-docs.otoko.com/api-reference/calls-to-your-backend: the routes OI calls, and verifying the signature.
- https://identity-docs.otoko.com/api-reference/tokens: checking tokens and lifetimes.
- https://identity-docs.otoko.com/api-reference/errors: every error code.
- 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 401invalid_credentials, as a wrong one does. - People manage their own passkeys through
/internal/v1/passkeys, with the API key and their access token in theX-Access-Tokenheader. - 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 (422passkey_origin_required), and only a mobile client may have them (422invalid_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.jsonstill 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/userinfoanswerssub,emailandlocalefor its access tokens.