Learn Expo · 9/11

User Authentication & Security

10 min read

User Authentication & Security

User authentication is the foundation of almost every modern application. Before we can show a user their private dashboard, personalized feed, or hidden settings, we must verify who they are and ensure their data remains locked away from everyone else.

In this guide, we will break down the end-to-end process of handling users in an Expo app—from the first input field they tap, to the secure vault where their access keys are stored.


1. Designing the Sign-In and Sign-Up Flows 🎨

Definition: The sign-in and sign-up flows are the user interfaces and logic sequences that allow individuals to create an account or verify their identity to access an application.

The Problem: You need to identify your users to serve them private data. However, users are notoriously impatient. If your sign-up form asks for their grandmother's maiden name, favorite color, and blood type, they will simply delete your app.

The Solution: A minimal, frictionless UI that collects only the essentials (usually an email and password), validates them instantly, and provides clear visual feedback (like loading spinners or error messages) while the app talks to the server.

The Industry Standard Approach

In the industry, we rarely build 10-step authentication forms. The standard is to keep it strictly to Email and Password (or just OAuth, which we will cover later).

Before you write logic, you need to understand the visual state of authentication. A typical screen has three states:

  1. Idle: Waiting for user input.
  2. Loading: The user pressed "Submit." The UI must freeze to prevent double-submissions, and a spinner should indicate that background work is happening.
  3. Result: Success (navigate away) or Error (show a red text banner explaining what went wrong).
tsx
import React, { useState } from 'react';
import { View, TextInput, Button, Text, ActivityIndicator, StyleSheet } from 'react-native';

export default function SignInScreen() {
  // 1. We start with alphabets: simple local state to hold text.
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  
  // 2. State for UI feedback
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSignIn = async () => {
    // Basic validation
    if (!email || !password) {
      setError('Please fill in all fields.');
      return;
    }

    setIsLoading(true);
    setError('');

    try {
      // Simulate an API call
      await new Promise(resolve => setTimeout(resolve, 1500));
      // Hand off to your Auth Context here!
    } catch (err) {
      setError('Failed to sign in. Did you forget your password again?');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Welcome Back 🔐</Text>
      
      {!!error && <Text style={styles.errorText}>{error}</Text>}

      <TextInput
        style={styles.input}
        placeholder="Email"
        autoCapitalize="none"
        keyboardType="email-address"
        value={email}
        onChangeText={setEmail}
      />
      <TextInput
        style={styles.input}
        placeholder="Password"
        secureTextEntry
        value={password}
        onChangeText={setPassword}
      />

      {isLoading ? (
        <ActivityIndicator size="large" color="#0000ff" />
      ) : (
        <Button title="Sign In" onPress={handleSignIn} />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, justifyContent: 'center' },
  title: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, textAlign: 'center' },
  input: { borderWidth: 1, borderColor: '#ccc', padding: 12, marginBottom: 15, borderRadius: 8 },
  errorText: { color: 'red', marginBottom: 10, textAlign: 'center' }
});

Progressive Concept: Think of this form as the envelope. The data inside is the letter. Before we send the letter to the post office (the server), we must make sure the envelope has a destination address (validation).


2. Route Guards: Protecting Screens with Expo Router Auth Context 🛡️

Definition: Route guards are conditional checks placed in your application's navigation layer that prevent unauthorized access to specific screens or route segments.

The Problem: Even if you have a beautifully designed sign-in screen, a user might manually trigger a deep link (e.g., myapp://(app)/dashboard). If an unauthenticated user bypasses the sign-in screen and lands on the dashboard, the app will try to fetch their private data, resulting in a spectacular crash or a severe security breach.

The Solution: We wrap our secure screens in a "guard." If the user is authenticated, the app renders the screen. If they are not, the routing system intercepts the request and safely redirects them back to the login page.

Expo Router SDK 53+ <Stack.Protected>

Historically, developers had to write messy, imperative redirects inside useEffect hooks. With the release of Expo Router SDK 53, Expo introduced a declarative way to handle this: Protected Routes.

Imagine you are running an exclusive VIP club. Stack.Protected is the bouncer at the door. You give the bouncer a guest list (your authentication state). When a user tries to walk into the VIP room (/dashboard), the bouncer checks the list. If they aren't on it, they are instantly escorted back to the lobby (/login).

Here is how you structure this cleanly using React Context and Expo Router.

Step 1: The Auth Context

First, we need a global state to know if the user is signed in.

tsx
// context/AuthContext.tsx
import { createContext, useContext, useState } from 'react';

const AuthContext = createContext<{ user: string | null; signIn: () => void; signOut: () => void }>({
  user: null,
  signIn: () => {},
  signOut: () => {},
});

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<string | null>(null);

  const signIn = () => setUser('fake-jwt-token');
  const signOut = () => setUser(null);

  return (
    <AuthContext.Provider value={{ user, signIn, signOut }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => useContext(AuthContext);

Step 2: The Layout Guard

Now, we apply the Stack.Protected component in our root layout.

tsx
// app/_layout.tsx
import { Stack } from 'expo-router';
import { AuthProvider, useAuth } from '../context/AuthContext';

function RootLayoutNav() {
  const { user } = useAuth();
  
  // user is true if logged in, false if not.
  const isLoggedIn = !!user;

  return (
    <Stack>
      {/* 🛑 Logged Out Users Go Here */}
      <Stack.Protected guard={!isLoggedIn}>
        <Stack.Screen name="login" options={{ headerShown: false }} />
      </Stack.Protected>

      {/* ✅ Logged In Users Go Here */}
      <Stack.Protected guard={isLoggedIn}>
        <Stack.Screen name="(app)" options={{ headerShown: false }} />
      </Stack.Protected>
    </Stack>
  );
}

export default function RootLayout() {
  return (
    <AuthProvider>
      <RootLayoutNav />
    </AuthProvider>
  );
}

If a user tries to navigate to /(app) while logged out, the navigation fails silently and they remain on (or are redirected to) the available public screens.


3. OAuth and Social Login Providers via Expo AuthSession 🌐

Definition: OAuth (Open Authorization) is an open standard for access delegation. expo-auth-session is a universal Expo library providing an API to handle browser-based authentication flows.

The Problem: Typing out emails and creating complex passwords on mobile keyboards is a miserable experience. People forget passwords daily. Every hurdle in the login process reduces the number of users who will actually use your app.

The Solution: Let Google, Apple, or GitHub do the heavy lifting. You outsource the login process to them. expo-auth-session manages the complex mechanism of opening a secure browser, letting the user log in on Google's website, and securely catching the response when Google redirects them back to your app.

Installation

Strictly fetch the latest dependencies:

bash
npx expo install expo-auth-session expo-crypto

(Note: expo-crypto is a required peer dependency because OAuth relies on cryptographic hashing for security verifications like PKCE).

The OAuth Flow Explained

Imagine going to an airport. Instead of the airline personally checking your background history (password auth), they rely on the government (Google/Apple). You go to the government, they verify you, and they give you a passport (Token). You hand the passport to the airline, and they let you on the plane.

Here is how expo-auth-session handles it:

  1. Initiation: The app creates a request.
  2. Open Browser: The app opens an external secure browser (WebBrowser) to the provider's URL.
  3. Redirect: Once verified, the provider redirects back to a special URL tied to your app scheme.
  4. Exchange: Your app parses the URL and extracts the authentication code.

Code Example: Google OAuth

tsx
import React, { useEffect } from 'react';
import { Button, View, Text } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as AuthSession from 'expo-auth-session';

// 1. Mandatory rule: dismiss the popup if it gets stuck
WebBrowser.maybeCompleteAuthSession();

export default function GoogleSignIn() {
  // 2. We build a discovery document (where are Google's servers?)
  const discovery = AuthSession.useAutoDiscovery('https://accounts.google.com');

  // 3. Create a secure redirect URI that routes back to our app
  const redirectUri = AuthSession.makeRedirectUri();

  // 4. Hook to manage the request state
  const [request, response, promptAsync] = AuthSession.useAuthRequest(
    {
      clientId: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
      redirectUri,
      scopes: ['openid', 'profile', 'email'],
    },
    discovery
  );

  useEffect(() => {
    // 5. When the browser closes, we check the response
    if (response?.type === 'success') {
      const { code } = response.params;
      console.log('We got the authorization code!', code);
      // Hand this code to your backend to exchange for a real user session
    }
  }, [response]);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Sign in with your favorite provider</Text>
      <Button 
        title="Sign In with Google" 
        disabled={!request} 
        onPress={() => promptAsync()} 
      />
    </View>
  );
}

4. Secure API Calls: Managing and Attaching JWT Tokens 📦

Definition: A JSON Web Token (JWT) is a compact, URL-safe standard used for representing securely transmitted information between parties. expo-secure-store is a library that provides a way to encrypt and securely store key-value pairs locally on the device.

The Problem: Once the user successfully logs in, the server gives your app a JWT. If you store this token in standard AsyncStorage, you are essentially leaving the key to your house under the doormat. It is unencrypted, meaning malicious scripts or device access could expose it. Furthermore, the server needs to see this token on every single request to verify the user.

The Solution: Store the token in a highly encrypted vault provided by the native operating system (Keychain on iOS, Keystore on Android). Then, intercept your outgoing API calls and staple the token to the request headers.

Installation

bash
npx expo install expo-secure-store

1. Storing the Token Securely

Think of SecureStore like a bank vault inside the phone. Once the token is inside, only your specific app can ask the vault manager to retrieve it.

tsx
import * as SecureStore from 'expo-secure-store';

// Saving the token
export async function saveToken(value: string) {
  try {
    await SecureStore.setItemAsync('jwt_token', value);
  } catch (error) {
    console.error('Failed to save the token to the vault', error);
  }
}

// Retrieving the token
export async function getToken() {
  try {
    return await SecureStore.getItemAsync('jwt_token');
  } catch (error) {
    console.error('Failed to retrieve the token', error);
    return null;
  }
}

2. Attaching the Token to API Calls

Now that we have the token stored securely, we need to send it back to the server. The industry standard is to place it in the Authorization header of your HTTP request using the Bearer schema.

tsx
export async function fetchPrivateProfile() {
  // 1. Get the token from the vault
  const token = await getToken();

  if (!token) {
    throw new Error('No token found. Please log in.');
  }

  // 2. Attach it to the request header
  const response = await fetch('https://api.yourdomain.com/v1/profile', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      // This is the magic line that proves who we are
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!response.ok) {
    // If the token expired, the server throws a 401 Unauthorized
    if (response.status === 401) {
      console.log('Token expired! Time to log out or refresh.');
    }
    throw new Error('Network response was not ok');
  }

  return response.json();
}

Under the hood: A JWT contains three parts separated by dots (header.payload.signature). The payload is just Base64 encoded JSON (meaning anyone can read it, so never put passwords inside a JWT!). The signature is mathematically created using a secret key on your backend. If someone alters the payload, the signature breaks, and your backend immediately rejects the forged token.


Reference & Further Reading 📚

Challenge

You are tasked with building the core authentication logic for an Expo application. Your goal is to create a custom React hook named useAuth that manages user session tokens and handles secure API interactions.

Requirements:

  1. Implement the signIn function:

    • This function receives a data object containing email and password.
    • It should call the provided mockApiLogin function.
    • If the login is successful, you must securely store the received JWT using SecureStore.setItemAsync. Use the key "userToken".
    • Finally, update the internal userToken state to reflect the new session.
  2. Implement the signOut function:

    • This asynchronous function should clear the user's session.
    • Remove the token from secure storage using SecureStore.deleteItemAsync with the key "userToken".
    • Set the internal userToken state to null.
  3. Implement the fetchProtectedData function:

    • This asynchronous function simulates fetching data from a protected API endpoint.
    • First, retrieve the stored JWT from secure storage using SecureStore.getItemAsync with the key "userToken".
    • If a token exists, call the mockApiFetchProtected function with the token and return its result.
    • If no token is found, return an object indicating failure: { success: false, error: 'No token found' }.

Expected result

Your completed useAuth hook should correctly implement all three asynchronous functions: signIn, signOut, and fetchProtectedData.

  • The signIn function should successfully handle the login flow: it calls the mock API, and upon receiving a token, it stores the token in SecureStore with the key "userToken" and updates the userToken state variable.
  • The signOut function should clear the session by deleting the "userToken" from SecureStore and setting the userToken state to null.
  • The fetchProtectedData function should retrieve the token from SecureStore. If the token exists, it should use it to call the protected API mock. If the token does not exist, it should return an appropriate error object without making an API call.

The final code should be a complete and functional React hook according to the specified requirements.

jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.