Skip to Content

Unlock with biometrics

Ask a returning user for Face ID, Touch ID or a fingerprint before an Expo app opens, with the password as a fallback.

A saved session keeps your app signed in for weeks, so anyone who picks up the unlocked phone can open it. Some apps ask the returning user to confirm it's them first: a "Welcome back" screen with Face ID, Touch ID or a fingerprint, and the password as a fallback.

This page adds that screen to the app from the Expo Router guide. With the client's locking option, a saved session restores as locked. The app can greet the user by name, but the tokens stay sealed until the user unlocks them. Locking explains how a locked session behaves. This page is the Expo side.

Here's how the pieces fit together. A random key is kept in a SecureStore item that needs biometrics to read, so reading it shows the biometric prompt. The client seals the tokens with that key, using AES-GCM, each time it saves them, and opens them when the user unlocks.

Before you begin

  • The app from the Expo Router guide, with the expo-secure-store config plugin in app.json. On iOS, the plugin adds the Face ID permission that the prompt needs.
  • A development build on a real device. Expo Go doesn't support SecureStore's biometric prompt where biometrics are available, and simulators don't ask for biometrics.

1. Install the packages

This page makes the key with expo-crypto, and seals the tokens with @noble/ciphers. They're your app's dependencies, not Session kit's:

npx expo install expo-crypto @noble/ciphers

2. Keep a key behind biometrics

This file makes the key, saves it behind the device's biometrics, reads it back to unlock, and seals the tokens with it:

src/session-key.ts
import {  } from "react-native";

import type {  } from "@monarcode/session-kit";
import {  } from "@noble/ciphers/aes.js";
import {
  ,
  ,
  ,
  ,
} from "@noble/ciphers/utils.js";
import {  } from "expo-crypto";
import * as  from "expo-secure-store";

const  = "session-key";
// Whether the key was saved behind biometrics, so it's read the same way.
const  = "session-key-biometric";

function (: boolean): . {
  return 
    ? {
        : true,
        : "Unlock your account",
      }
    : {};
}

// In memory from an unlock or a password sign-in until the app locks.
let :  | undefined;

/**
 * Saves the key behind the device's biometrics, or, on a device with none
 * enrolled, without them. On Android, saving shows the prompt.
 */
async function (: ): <void> {
  const  = .();
  // On iOS, replacing an item that needs biometrics shows the prompt, and
  // saving a new one doesn't. So a password sign-in asks for nothing more.
  await .();
  await .(
    ,
    (),
    (),
  );
  await .(, ());
}

/**
 * Reads the key, which shows the prompt when it needs biometrics. Resolves
 * `null` when no key was saved yet.
 */
async function (): <string | null> {
  const  = await .();
  if ( === null) return null;
  const  = await .(
    ,
    ( === "true"),
  );
  // SecureStore reads `null` for a key that a change to the device's
  // biometrics made unreadable.
  if ( === null) throw new ("The session key can't be read");
  return ;
}

/**
 * Loads the key to unlock. Throws when the user cancels the prompt, or when
 * the device's biometrics changed and the key can't be read.
 */
export async function (): <void> {
  const  = await ();
  if () {
     = ();
    return;
  }
  // A session saved before locking was added has no key yet. Make one: on
  // iOS, saving doesn't prompt, so read it back to show the prompt.
  const  = (32);
  await ();
  if (. === "ios") await ();
   = ;
}

/**
 * Signs in with a new key, and saves it only after the sign-in succeeds: a
 * failed sign-in keeps the key that the saved session is sealed with.
 */
export async function <>(: () => <>): <> {
  const  = ;
  const  = (32);
   = ;
  let : ;
  try {
     = await ();
  } catch () {
    if ( === )  = ;
    throw ;
  }
  try {
    await ();
  } catch () {
    // The session works until the app closes; then the password unlocks it.
    .("Could not save the session key", );
  }
  return ;
}

/** Forgets the key in memory, after `auth.lock()` has settled. */
export function (): void {
   = ;
}

function ():  {
  if (!) throw new ("The session key isn't loaded");
  return ;
}

/** AES-256-GCM: a random 12-byte nonce, then the ciphertext, as hex. */
export const :  = {
  () {
    const  = (12);
    const  = ((), ).(());
    return () + ();
  },
  () {
    const  = ();
    const  = .(0, 12);
    return (((), ).(.(12)));
  },
};

The rest of the app uses four of its exports:

  • loadKey() reads the key before an unlock, which shows the prompt.
  • withNewKey() wraps a password sign-in, so the new session is sealed with a new key.
  • dropKey() forgets the key when the app locks or signs out.
  • sessionLocking is the client's locking option.

A device with no biometrics enrolled can't save an item that needs them. So on those devices the key is saved without them, and unlocking asks for nothing beyond the device's own lock screen. If your app needs more there, sign out instead of locking.

Users who signed in before you added locking need no migration. Their saved session restores as locked too, and has no key yet, so loadKey() makes one at their first unlock.

3. Seal the session with the key

Pass sessionLocking to the client as locking. Then sign in through withNewKey(), and add a signOut() that forgets the key. The changed lines are marked:

src/auth.ts
import {  } from "@monarcode/session-kit";
import {  } from "@monarcode/session-kit/expo";
import {  } from "@monarcode/session-kit/http";
import {  } from "zod";

import { , ,  } from "./session-key";

const  = "https://dummyjson.com";

export const  = .({
  : .(),
  : .(),
  : .(),
  : .(),
});

const  = .({
  : .(),
  : .(),
});
const  = .(.);

export const  = ({
  : "my-app",
  : ,
  : (),
  : ,
  // Changed: seals the saved tokens with the key.
  : ,
  : async ({ ,  }) => {
    const  = await (`${}/auth/refresh`, {
      : "POST",
      ,
      : { "Content-Type": "application/json" },
      : .({  }),
    });
    // DummyJSON answers 401 or 403 when the refresh token is no good.
    if (. === 401 || . === 403) return null;
    if (!.) throw new (`Refresh failed (${.})`);
    return .(await .());
  },
});

export const  = (, { : `${}/` });

export async function (: string, : string) {
  const  = await (`${}/auth/login`, {
    : "POST",
    : { "Content-Type": "application/json" },
    : .({ ,  }),
  });
  if (!.) throw new (`Sign-in failed (${.})`);
  const { , , ... } = .(
    await .(),
  );
  // Changed: the new session is sealed with a new key.
  await (() => .({ , ,  }));
}

/** Changed: signs out, and forgets the key. It works offline. */
export async function (): <void> {
  await .().(() => {});
  ();
}

Saving a session seals it, a sign-in's too, and seal throws while no key is loaded. That's why every sign-in goes through withNewKey(). Without a key, the sign-in would fail with PERSISTENCE_FAILED.

4. Guard the unlock screen

A locked session isn't signed in, but it keeps its user. So the stack needs a third screen, and a guard for each state that's true in that state only:

app/_layout.tsx
import {  } from "@monarcode/session-kit";
import {  } from "@monarcode/session-kit/expo";
import { ,  } from "@monarcode/session-kit/react";
import { ,  } from "expo-router";

import {  } from "../src/auth";
import {  } from "../src/unavailable";

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    : typeof ;
  }
}

// Keeps the splash screen up until SessionGate hides it.
void .();

export default function () {
  return (
    < ={}>
      < ={() => < {...} />}>
        < />
      </>
    </>
  );
}

function () {
  const  = ();
  const  = (() => . === "locked");
  return (
    < ={{ : false }}>
      <. ={}>
        <. ="(app)" />
      </.>
      <. ={}>
        <. ="welcome-back" />
      </.>
      {/* Not while locked, so a locked app opens on welcome-back. */}
      <. ={! && !}>
        <. ="login" />
      </.>
    </>
  );
}

Each state needs exactly one screen open to it. When a guard turns the user away, Expo Router sends them to the first screen they may see, in its own order of routes, not in the order of your JSX. If the sign-in screen were open to a locked user too, a locked app could open on it rather than on the welcome-back screen.

5. Add the welcome-back screen

The welcome-back screen greets the user, reads the key, which shows the biometric prompt, and unlocks. A user who can't unlock signs in with their password on the same screen:

app/welcome-back.tsx
import {  } from "react";
import { , ,  } from "react-native";

import {  } from "@monarcode/session-kit/react";

import {  } from "../src/auth";
import {  } from "../src/session-key";
import  from "./login";

export default function () {
  const  = (() => .?.);
  const [, ] = (false);
  const [, ] = (false);

  async function () {
    (false);
    try {
      await ();
      await .();
      // No navigation: Stack.Protected leaves this screen, and
      // SessionGate opens the deep link the user was headed to.
    } catch {
      // Cancelled, or the biometrics changed: offer the password. A refresh
      // that failed after unlocking leaves the session `unavailable`, which
      // SessionGate shows instead.
      if (..(). === "locked") (true);
    }
  }

  // The sign-in form. Signing in replaces the locked session.
  if () return < />;

  return (
    < ={{ : 1, : "center", : 24, : 12 }}>
      < ="header">
        Welcome back{ ? `, ${}` : ""}
      </>
      < ="Unlock" ={() => void ()} />
      { ? < ="alert">Could not unlock</> : null}
      < ="Use your password" ={() => (true)} />
    </>
  );
}

A password sign-in works while the session is locked, and replaces it. It goes through withNewKey(), so the new session gets a new key. A failed unlock doesn't always leave the session locked, which is why the screen checks status after a rejection. Locking explains both.

6. Forget the key on sign-out

After a sign-out, nothing needs the key. Both Sign out buttons call the signOut() from src/auth.ts, which forgets it. On the home screen:

app/(app)/index.tsx
import { , ,  } from "react-native";

import {  } from "@monarcode/session-kit/react";
import {  } from "expo-router";

import {  } from "../../src/auth";

export default function () {
  const  = (() => .?.);
  return (
    < ={{ : 1, : "center", : 24, : 12 }}>
      < ="header">Welcome, {}</>
      < ="/profile">Profile</>
      {/* No navigation: Stack.Protected then shows the sign-in screen. */}
      < ="Sign out" ={() => void ()} />
    </>
  );
}

And on the unavailable screen:

src/unavailable.tsx
import { , ,  } from "react-native";

import type {  } from "@monarcode/session-kit/expo";

import {  } from "./auth";

export function ({ ,  }: ) {
  return (
    < ={{ : 1, : "center", : 24, : 12 }}>
      < ="header">Can't reach your account</>
      <>{?. ?? "Check your connection and try again."}</>
      < ="Try again" ={} />
      < ="Sign out" ={() => void ()} />
    </>
  );
}

7. Lock after time in the background

To ask again after the app has been away for a while, lock it when it returns to the foreground, then forget the key:

src/auto-lock.ts
import {  } from "react-native";

import {  } from "./auth";
import {  } from "./session-key";

/** How long the app may stay in the background before it locks. */
const  = 5 * 60_000;

/** Locks the session when the app returns after `LOCK_AFTER` away. */
export function (): () => void {
  let : number | undefined;
  const  = .("change", () => {
    if ( === "background")  = .();
    else if ( === "active" &&  !== ) {
      if (.() -  > )
        void .().(() => {
          // An unlock or sign-in can land before the lock finishes.
          if (..(). === "locked") ();
        });
       = ;
    }
  });
  return function () {
    .();
  };
}

lock() locks at once, and resolves after a refresh that's still running has saved its tokens. That save seals them with the key, so dropKey() waits for it. If the user unlocks or signs in before then, the session isn't locked any more, and the key stays for the next save.

Start the watcher in the signed-in group's layout. That layout is mounted only while the user is signed in, so the watcher starts after a sign-in or an unlock, and stops when the app locks or signs out:

app/(app)/_layout.tsx
import {  } from "react";

import {  } from "expo-router";

import {  } from "../../src/auto-lock";

export default function () {
  (function () {
    return ();
  }, []);
  return < />;
}

While the session is locked, SessionGate checks nothing when the app returns to the foreground. Requests through authFetch reject with LOCKED until the user unlocks.

8. Check the app

Build the app for a device that has Face ID, Touch ID or a fingerprint set up, and check each path:

  1. Sign in with your password. On Android, saving the key shows the biometric prompt.
  2. Close the app and open it again. The welcome-back screen greets you by name.
  3. Tap Unlock, and pass the prompt. The home screen shows.
  4. Put the app in the background for more than five minutes, then return to it. The welcome-back screen shows. To check this sooner, lower LOCK_AFTER while you test.
  5. Tap Use your password, and sign in. The home screen shows.
  6. Close the app, then open myapp://profile, for example from a link in Notes. The welcome-back screen shows. Unlock, and the profile screen opens.

Next steps

  • Locking: how a locked session behaves, and which methods reject while it's locked.
  • Expo Router: the app this page builds on, and how secureStorage() and SessionGate work.
  • AuthLocking reference: what seal and open receive and return.

On this page