Skip to main content

Sign-in in a mobile app

Sign in from a React Native app through the system browser, and keep the tokens in secure storage.

RecipeDraftView source
This page is a draft. The code exists, and not all of it has been run for this page yet. The page says what was checked.
Works with
JavaScript / TypeScriptReact Native

What it shows​

  1. The app builds the address of the hosted sign-in page with a new PKCE verifier, and opens it in the system browser.
  2. The redirect returns to the app through its own scheme, com.acme.notes://auth/callback. The app checks the state and exchanges the code.
  3. A token store of the SDK, backed by expo-secure-store, keeps the tokens in the Keychain on iOS and the Keystore on Android.
  4. The session of the SDK renews the access token with the refresh token before it expires, and loads the tokens again when the app starts.
  5. Sign-out revokes the refresh token and clears the store.

Before you start​

  • Node.js and the tools for a development build of Expo: the Android SDK, or Xcode for npx expo run:ios. The app registers its scheme in app.json, and a development build installs that scheme on the device.
  • A public application with the redirect URI com.acme.notes://auth/callback. The setup script creates it. A native app has no web origin, so the application needs no CORS setting.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
EXPO_PUBLIC_LUMOAUTH_DOMAINThe address of LumoAuth, for example https://app.lumoauth.dev. The setup script prints it.
EXPO_PUBLIC_LUMOAUTH_ORG_IDYour organization. The setup script prints it.
EXPO_PUBLIC_LUMOAUTH_CLIENT_IDThe client ID of the public application. The setup script prints it. A mobile app has no client secret.

The setup script creates the public application with the redirect URI of the app, and prints the variables that the app reads.

node sign-in/react-native/setup.mjs
setup.mjs
// Creates the application that the mobile app signs in with: a public
// application with the redirect URI of the app's own scheme. Run it again at
// any time.
//
// node sign-in/react-native/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
import { call, list, printEnv, url, org } from '../../_lib/admin.mjs';

const name = 'Acme Notes mobile app';
// The scheme of app.json. A native app has no web origin, so it needs no
// CORS setting.
const redirectUris = ['com.acme.notes://auth/callback'];

let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
} else {
// An app on a phone cannot keep a secret, so the application is public.
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: false })).data;
}

console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
EXPO_PUBLIC_LUMOAUTH_DOMAIN: url,
EXPO_PUBLIC_LUMOAUTH_ORG_ID: org,
EXPO_PUBLIC_LUMOAUTH_CLIENT_ID: client.clientId,
});

Copy the export lines that the script prints into the terminal where you start the app. Expo puts the EXPO_PUBLIC_ variables into the app when it builds it.

To create the application in the portal instead, open Applications and select New application. Choose Single-page or mobile app, enter the redirect URI, and select Create application.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. The app was type-checked, not run. The same SDK calls ran in Node.js against an organization, with a desktop browser in place of the system browser. The code exchange, the secure store, the refresh and the sign-out worked there. The redirect to the app's scheme came only from a second visit, after the person had signed in: right after the sign-in form, the browser blocked it.

sign-in/react-native/js/auth.ts
// Sign-in for a React Native app (Expo). The system browser shows the hosted
// sign-in page, the redirect returns to the app through its own scheme, and
// the tokens are kept in the secure storage of the device.
import { getRandomValues } from 'expo-crypto';
import * as SecureStore from 'expo-secure-store';
import * as WebBrowser from 'expo-web-browser';
import { AuthModule, EMPTY_TOKENS, LumoAuthSession, type StoredTokens, type TokenStorage } from '@lumoauth/client';

// The SDK makes the PKCE verifier and the state with crypto.getRandomValues.
// React Native has no such function, so expo-crypto provides it.
if (!globalThis.crypto?.getRandomValues) {
Object.assign(globalThis, { crypto: { ...globalThis.crypto, getRandomValues } });
}

// The scheme of app.json. Register this exact address as a redirect URI of
// the application.
const redirectUri = 'com.acme.notes://auth/callback';

export const auth = new AuthModule({
baseUrl: process.env.EXPO_PUBLIC_LUMOAUTH_DOMAIN,
orgId: process.env.EXPO_PUBLIC_LUMOAUTH_ORG_ID,
clientId: process.env.EXPO_PUBLIC_LUMOAUTH_CLIENT_ID!,
});

// A token store of the SDK, backed by the Keychain on iOS and the Keystore
// on Android. It survives a restart of the app.
const secureStorage: TokenStorage = {
name: 'expo-secure-store',
async get() {
const saved = await SecureStore.getItemAsync('lumoauth_tokens');
return saved ? (JSON.parse(saved) as StoredTokens) : EMPTY_TOKENS;
},
async set(tokens) {
await SecureStore.setItemAsync('lumoauth_tokens', JSON.stringify(tokens));
},
async clear() {
await SecureStore.deleteItemAsync('lumoauth_tokens');
},
};

// The session of the SDK keeps the tokens in that store and renews the access
// token with the refresh token before it expires. An app has one window, so
// there are no tabs to keep in step.
export const session = new LumoAuthSession({ auth, storage: secureStorage, redirectUri, crossTab: false });

export async function signIn(): Promise<void> {
// 1. The address of the hosted sign-in page, with a new PKCE verifier.
const { url, codeVerifier, state } = await auth.buildAuthorizationUrl({ redirectUri });

// 2. The system browser opens it. The app never shows a sign-in form, and
// the call returns when the browser opens the redirect URI.
const result = await WebBrowser.openAuthSessionAsync(url, redirectUri);
if (result.type !== 'success') return; // The person closed the browser.

const params = new URL(result.url).searchParams;
const code = params.get('code');
if (!code || params.get('state') !== state) throw new Error('The sign-in did not come back from this app.');

// 3. Only this app holds the verifier, so only it can redeem the code.
const tokens = await auth.exchangeCodeForTokens({ code, codeVerifier, redirectUri });
await session.adopt(tokens);
}

export async function signOut(): Promise<void> {
const { refreshToken } = session.getTokens();
// Revoking the refresh token also revokes the access tokens issued with it.
if (refreshToken) await auth.revokeToken(refreshToken, undefined, { tokenTypeHint: 'refresh_token' });
await session.clearSession();
}
sign-in/react-native/js/App.tsx
// The screen of the app: a sign-in button, or the signed-in person.
//
// cd sign-in/react-native/js && npm install && npx expo run:android
import { useEffect, useState, useSyncExternalStore } from 'react';
import { Button, Text, View } from 'react-native';
import { auth, session, signIn, signOut } from './auth';

export default function App() {
const status = useSyncExternalStore(session.subscribe, session.getSnapshot);
const [email, setEmail] = useState('');
const [answer, setAnswer] = useState('');

// Load the tokens of an earlier start from the secure storage.
useEffect(() => {
void session.hydrate();
}, []);

// getToken() returns a valid access token. It renews it first when it is
// about to expire. Send it to your own API in the same way.
async function callApi() {
const token = await session.getToken();
if (!token) return;
const user = await auth.getUserInfo(token);
setEmail(user.email ?? '');
setAnswer(`UserInfo answered for ${user.email}`);
}

useEffect(() => {
if (status.isSignedIn) void callApi();
}, [status.isSignedIn]);

if (!status.isLoaded) return <Text>Loading…</Text>;
return (
<View style={{ padding: 24, paddingTop: 64, gap: 12 }}>
{status.isSignedIn ? (
<>
<Text>Signed in as {email}</Text>
<Button title="Call the API" onPress={callApi} />
<Text>{answer}</Text>
<Button title="Sign out" onPress={signOut} />
</>
) : (
<>
<Text>Nobody is signed in.</Text>
<Button title="Sign in" onPress={signIn} />
</>
)}
</View>
);
}
sign-in/react-native/js/app.json
{
"expo": {
"name": "Acme Notes",
"slug": "acme-notes",
"scheme": "com.acme.notes",
"ios": { "bundleIdentifier": "com.acme.notes" },
"android": { "package": "com.acme.notes" }
}
}
sign-in/react-native/js/package.json
{
"name": "lumoauth-recipe-react-native",
"private": true,
"main": "expo/AppEntry",
"scripts": {
"start": "expo start",
"android": "expo run:android",
"ios": "expo run:ios",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@lumoauth/client": "^1.7.0",
"expo": "~58.1.0",
"expo-crypto": "~58.0.9",
"expo-secure-store": "~58.0.3",
"expo-web-browser": "~58.1.0",
"react": "19.3.0",
"react-native": "0.88.1"
},
"devDependencies": {
"@types/react": "^19.3.3",
"typescript": "^5.9.0"
}
}
cd sign-in/react-native/js && npm install && npx expo run:android

Compiles. Not run against an organization. It passes tsc --noEmit with Expo 58 and React Native 0.88. It did not run on a phone or a simulator: none was available.

Check the result​

Tap Sign in. The system browser opens the sign-in page of your organization. After sign-in, the browser closes and the app shows these lines:

Output
Signed in as maya.chen@example.com
UserInfo answered for maya.chen@example.com
  • The app never shows a sign-in form of its own, in a web view or elsewhere.
  • Close the app and start it again. It is still signed in: the session reads the tokens from the secure store.
  • Tap Sign out. The refresh token no longer works, and the next start shows Sign in.

Limits​

  • React Native has no crypto.getRandomValues, which the SDK needs for the PKCE verifier. auth.ts takes it from expo-crypto.
  • Expo Go does not install the scheme of your app. Use a development build.
  • Sign-out ends the session of the app only. The system browser keeps its LumoAuth session, so the next sign-in may not ask for the password. To end it too, open the address that auth.buildEndSessionUrl() returns in the browser.
  • A custom scheme can be claimed by another app on the same device. PKCE protects the code: only the app that holds the verifier can redeem it.