メインコンテンツへスキップ
このクイックスタートは React Native フレームワーク向けです。Auth0 を Expo アプリケーションに統合する場合は、Expo クイックスタートを参照してください。

AI を使って Auth0 を統合する

Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使用している場合は、agent skills を使って、数分で Auth0 認証を自動的に追加できます。インストール:
npx skills add https://github.com/auth0/agent-skills --skill auth0-react-native
次に、AI アシスタントに以下のように依頼します。
Add Auth0 authentication to my React Native app
AI アシスタントが、Auth0 アプリケーションの作成、認証情報の取得、react-native-auth0 のインストール、ネイティブ依存関係の構成、認証フローのセットアップを自動的に行います。agent skills の完全なドキュメント →

はじめに

1

新しい React Native プロジェクトを作成する

このクイックスタート用に、新しい React Native プロジェクトを作成します。ターミナルで次を実行します:
npx @react-native-community/cli init Auth0ReactNativeSample
cd Auth0ReactNativeSample
次の内容でプロジェクトを設定します。
  • 名前: Auth0ReactNativeSample
  • パッケージ名: com.auth0.samples.reactnative
これにより、最新の安定版の React Native アプリが作成されます。Auth0 SDK を使用するには、React Native 0.78.0 以降および React 19.0.0 以降が必要です。
2

Auth0 SDKをインストールする

Auth0 React Native SDK をプロジェクトに追加します。
npm install react-native-auth0
iOS では、ネイティブの依存関係をインストールします。
cd ios && pod install && cd ..
SDK は両方のプラットフォームで自動的にリンクされます。pod install の手順で、必要な iOS ネイティブモジュール (Auth0.swift、JWTDecode、SimpleKeychain) がインストールされます。
3

Auth0アプリケーションを設定する

React Native アプリで使用する Auth0 アプリケーションを作成して設定します。
  1. Auth0 Dashboard に移動します
  2. Applications > Applications > Create Application をクリックします
  3. ポップアップでアプリの名前 (例: Auth0 React Native Sample) を入力し、アプリの種類として Native を選択して、Create をクリックします
  4. Application Details ページで Settings タブに切り替えます
  5. ドメインクライアントID の値を控えます
Allowed Callback URLs:
org.reactjs.native.example.auth0reactnativesample.auth0://{yourDomain}/ios/org.reactjs.native.example.auth0reactnativesample/callback,
com.auth0reactnativesample.auth0://{yourDomain}/android/com.auth0reactnativesample/callback
許可されたログアウトURL:
org.reactjs.native.example.auth0reactnativesample.auth0://{yourDomain}/ios/org.reactjs.native.example.auth0reactnativesample/callback,
com.auth0reactnativesample.auth0://{yourDomain}/android/com.auth0reactnativesample/callback
{yourDomain} を実際の Auth0 ドメイン (例: dev-abc123.us.auth0.com) に置き換えます。
Allowed Callback URLs は、認証後にユーザーが安全にアプリケーションへ戻れるようにするための重要なセキュリティ対策です。一致する URL がない場合、ログイン処理は失敗し、ユーザーはアプリにアクセスできず、代わりに Auth0 のエラーページが表示されます。Allowed Logout URLs は、サインアウト時にシームレスなユーザー体験を提供するうえで重要です。一致する URL がない場合、ユーザーはログアウト後にアプリケーションへリダイレクトされず、汎用の Auth0 ページに移動します。URL スキームには、コールバックが対象のアプリに確実にルーティングされるよう、バンドル識別子の後に .auth0 を含めます。このクイックスタートでは、バンドル識別子は org.reactjs.native.example.auth0reactnativesample です。
重要: コールバック URL スキームには、バンドル識別子の後に .auth0 を含める必要があります (例: org.reactjs.native.example.auth0reactnativesample.auth0://) 。これは、SDK が認証コールバックを適切に処理するために必要です。
4

ネイティブプラットフォームを設定する

認証コールバックを処理できるように、iOS と Android の両方を設定します。Android の設定:android/app/build.gradle を開き、defaultConfig 内にマニフェスト プレースホルダーを追加します。
android/app/build.gradle
android {
    defaultConfig {
        applicationId "com.auth0reactnativesample"
        // ... その他の設定
        
        // Auth0 マニフェストのプレースホルダーを追加する
        manifestPlaceholders = [
            auth0Domain: "{yourDomain}",
            auth0Scheme: "${applicationId}.auth0"
        ]
    }
}
{yourDomain} は、Auth0 のドメイン (例: dev-abc123.us.auth0.com) に置き換えてください。iOS の設定:
ios/Auth0ReactNativeSample/AppDelegate.mm を開き、URL を処理するメソッドを追加します。
ios/Auth0ReactNativeSample/AppDelegate.mm
#import <React/RCTLinkingManager.h>

// このメソッドを @implementation ブロック内に追加します
- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  return [RCTLinkingManager application:app openURL:url options:options];
}
ios/Auth0ReactNativeSample/Info.plist を開き、URL スキームを追加します。閉じる </dict> タグの直前に次を追加してください:
ios/Auth0ReactNativeSample/Info.plist
<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleTypeRole</key>
    <string>None</string>
    <key>CFBundleURLName</key>
    <string>auth0</string>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>$(PRODUCT_BUNDLE_IDENTIFIER).auth0</string>
    </array>
  </dict>
</array>
URL スキームには、バンドル識別子に .auth0 を付加したものを使用します。これにより、ブラウザーでの認証完了後に、コールバックが対象のアプリへルーティングされます。
5

Appコンポーネントを設定する

選択した実装方法に応じて、メインのアプリコンポーネントを設定します。
App.tsx の内容を次のように置き換え、アプリケーションを Auth0Provider コンポーネントでラップします。
App.tsx
import React from 'react';
import {Auth0Provider} from 'react-native-auth0';
import {SafeAreaView, StyleSheet} from 'react-native';
import MainScreen from './src/MainScreen';

const App = () => {
  return (
    <Auth0Provider
      domain="{yourDomain}"
      clientId="{yourClientId}">
      <SafeAreaView style={styles.container}>
        <MainScreen />
      </SafeAreaView>
    </Auth0Provider>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

export default App;
{yourDomain} は Auth0 のドメインに、{yourClientId} は Auth0 Dashboard のクライアントIDに置き換えます。
Auth0Provider は SDK を初期化し、useAuth0 Hook を介してすべての子コンポーネントに認証コンテキストを提供します。
6

ログインとログアウトを実装する

ログインとログアウトを処理する画面コンポーネントを作成します。フックベースのアプローチ (推奨) またはクラスベースのアプローチを選択できます。
useAuth0 Hookを使用して src/MainScreen.tsx を作成します。
src/MainScreen.tsx
import React from 'react';
import {
  View,
  Text,
  Button,
  StyleSheet,
  ActivityIndicator,
  Image,
} from 'react-native';
import {useAuth0} from 'react-native-auth0';

const MainScreen = () => {
  const {authorize, clearSession, user, isLoading} = useAuth0();

  const login = async () => {
    try {
      await authorize({scope: 'openid profile email'});
    } catch (e) {
      console.error(e);
    }
  };

  const logout = async () => {
    try {
      await clearSession();
    } catch (e) {
      console.error(e);
    }
  };

  if (isLoading) {
    return (
      <View style={styles.container}>
        <ActivityIndicator size="large" color="#0066cc" />
        <Text style={styles.loadingText}>Loading...</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Auth0 React Native</Text>

      {user ? (
        <View style={styles.profileContainer}>
          {user.picture && (
            <Image source={{uri: user.picture}} style={styles.avatar} />
          )}
          <Text style={styles.welcomeText}>Welcome, {user.name}!</Text>
          <Text style={styles.emailText}>{user.email}</Text>
          <View style={styles.buttonContainer}>
            <Button title="Log Out" onPress={logout} color="#dc3545" />
          </View>
        </View>
      ) : (
        <View style={styles.loginContainer}>
          <Text style={styles.subtitle}>
            Tap the button below to log in
          </Text>
          <View style={styles.buttonContainer}>
            <Button title="Log In" onPress={login} color="#0066cc" />
          </View>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    marginBottom: 20,
    color: '#333',
  },
  subtitle: {
    fontSize: 16,
    color: '#666',
    marginBottom: 30,
    textAlign: 'center',
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: '#666',
  },
  profileContainer: {
    alignItems: 'center',
  },
  avatar: {
    width: 100,
    height: 100,
    borderRadius: 50,
    marginBottom: 20,
  },
  welcomeText: {
    fontSize: 22,
    fontWeight: '600',
    marginBottom: 8,
    color: '#333',
  },
  emailText: {
    fontSize: 16,
    color: '#666',
    marginBottom: 30,
  },
  loginContainer: {
    alignItems: 'center',
  },
  buttonContainer: {
    width: 200,
    marginTop: 10,
  },
});

export default MainScreen;
authorize() メソッド (hooks) または auth0.webAuth.authorize() (class) は、セキュアなブラウザー (iOS では ASWebAuthenticationSession、Android では Chrome Custom Tabs) で Auth0 の Universal Login を開きます。clearSession() メソッドは、ユーザーをログアウトし、ブラウザーのセッションと保存済みの認証情報の両方をクリアします。
7

アプリを起動する

デバイスまたはエミュレーターで React Native アプリをビルドして実行します。iOS の場合 (macOS が必要) :
npx react-native run-ios
Android の場合:
npx react-native run-android
想定されるフロー:
  1. アプリを起動すると、「Log In」ボタンが表示されます
  2. Log In をタップ → ブラウザーが開き、Auth0 Universal Login が表示されます
  3. ログインを完了します (サインアップまたはサインイン)
  4. ブラウザーが閉じる → 自動的にアプリに戻ります
  5. ユーザープロフィールに名前、メールアドレス、アバターが表示されます
iOS Simulator で ASWebAuthenticationSession を使用するには、有効な Apple Developer アカウントが必要です。アカウントなしでシミュレータ上でテストする場合は、代わりに実機または Android エミュレータを使用してください。
チェックポイントこれで、Auth0 のログイン機能がデバイスまたはエミュレーターで完全に動作しているはずです。このアプリは安全なブラウザー認証を使用し、認証情報を自動的に管理します。

トラブルシューティングと高度な設定

「Callback URL mismatch」エラー

解決策:
  1. 正確な URL (.auth0 サフィックスを含む) が Auth0 Dashboard の Allowed Callback URLs に設定されていることを確認します
  2. iOS と Android の両方の URL が追加されていることを確認します
  3. {yourDomain} が実際の Auth0 ドメインに置き換えられていることを確認します

ログイン後にアプリに戻らない (iOS)

修正:
  1. Info.plist$(PRODUCT_BUNDLE_IDENTIFIER).auth0 を含む CFBundleURLSchemes エントリがあることを確認します
  2. AppDelegate.mm に URL を処理するメソッドが含まれていることを確認します
  3. URL スキームがバンドル識別子と一致していることを確認します

Android のビルドが失敗する

修正:
  1. build.gradleauth0Domainauth0Scheme のマニフェスト placeholders を追加します
  2. Gradle ファイルとプロジェクトを同期します
  3. ビルドをクリーンします: ./gradlew clean

「PKCE not allowed」エラー

修正:
  1. Auth0 Dashboard → Applications → Your Application に移動します
  2. アプリケーションの種類を Native に変更します
  3. 変更を保存して、もう一度試します

Pod install が失敗する (iOS)

修正:
  1. CocoaPods を更新します: sudo gem install cocoapods
  2. pod リポジトリを更新します: pod install --repo-update
  3. 問題が解消しない場合は、Podfile.lockios/Pods フォルダーを削除してから、再度 pod install を実行します

User cancelled エラー

ログイン関数で適切に処理します:
const login = async () => {
  try {
    await authorize({scope: 'openid profile email'});
  } catch (e) {
    if (e.message === 'a0.session.user_cancelled') {
      // ユーザーがログイン画面を閉じた場合の処理
      console.log('Login cancelled by user');
    } else {
      console.error('Login failed:', e);
    }
  }
};

iOS のアラートダイアログ

iOS では、ユーザーに “App Name” Wants to Use “auth0.com” to Sign In という権限ダイアログが表示されます。これは ASWebAuthenticationSession の想定された動作です。続行するには、ユーザーが Continue をタップする必要があります。この動作を変更するには、ephemeral session (SSO を無効化) を使用できます:
await authorize({scope: 'openid profile email'}, {ephemeralSession: true});
API 呼び出し用のトークンを取得するには、getCredentials() メソッドを使用します:
import {useAuth0} from 'react-native-auth0';

const MyComponent = () => {
  const {getCredentials} = useAuth0();

  const callApi = async () => {
    try {
      const credentials = await getCredentials();
      const response = await fetch('https://your-api.com/endpoint', {
        headers: {
          Authorization: `Bearer ${credentials.accessToken}`,
        },
      });
      // レスポンスを処理
    } catch (e) {
      console.error('Failed to get credentials', e);
    }
  };
};
リフレッシュトークンを受け取るには、ログイン時に offline_access スコープを含めます: authorize({scope: 'openid profile email offline_access'})。これにより、トークンを自動更新できるようになります。
ユーザーがすでにログインしているかどうかを確認するには、hasValidCredentials() を使用します:
import {useAuth0} from 'react-native-auth0';
import {useEffect} from 'react';

const App = () => {
  const {hasValidCredentials, getCredentials} = useAuth0();

  useEffect(() => {
    const checkAuth = async () => {
      const isLoggedIn = await hasValidCredentials();
      if (isLoggedIn) {
        const credentials = await getCredentials();
        // ユーザーは認証済みです。データを読み込みます
      }
    };
    checkAuth();
  }, []);
};