claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialsecurity

🔐auth0-ionic-react

プラグイン
auth0
ライセンス
Apache-2.0

説明

次のような場合に使用: Capacitorを使用したIonic ReactアプリにAuth0のログイン・ログアウト、またはディープリンクを追加する場合。 ネイティブのiOS/Android向けに、`@auth0/auth0-react`をCapacitor BrowserおよびApp pluginと統合します。

原文を表示

Use when adding Auth0 login, logout, or deep linking to an Ionic React app with Capacitor. Integrates @auth0/auth0-react with Capacitor Browser and App plugins for native iOS/Android.

ユースケース

  • Ionic ReactアプリにAuth0ログインを追加する
  • Ionic ReactアプリにAuth0ログアウトを追加する
  • Ionic Reactアプリにディープリンクを追加する
  • ネイティブiOS/Android向けに認証を統合する

本文(日本語訳)

Auth0 Ionic React(Capacitor)統合

Capacitorを使用したIonic ReactアプリケーションにAuth0認証を追加します。 このスキルは、iOSおよびAndroidのディープリンク処理に対応したネイティブモバイル認証を対象とし、 @auth0/auth0-react SDKと @capacitor/browser@capacitor/app pluginを組み合わせて使用します。

前提条件

  • Node.js 18以上
  • Ionic CLI(npm install -g @ionic/cli
  • Capacitorが設定済みの既存のIonic Reactアプリケーション
  • Auth0アカウントおよびテナント
  • iOS向け: Xcode 14以上およびCocoaPods
  • Android向け: API level 21以上のAndroid Studio
  • Auth0 CLI — brew install auth0/auth0-cli/auth0

使用しない場合

ユースケース 推奨スキル
React SPA(Capacitor/Ionicなし) auth0-react
React Native(bare CLI) auth0-react-native
Expo(React Native) auth0-expo
Ionic + Angular + Capacitor auth0-ionic-angular
Ionic + Vue + Capacitor auth0-ionic-vue
Next.js(サーバーサイド) auth0-nextjs
iOSネイティブ(Swift) auth0-swift
Androidネイティブ(Kotlin) auth0-android

クイックスタート手順

ステップ1: Auth0を設定する

Auth0 CLIを使った自動セットアップについては、完全なスクリプトが記載されたセットアップガイドを参照してください。

手動セットアップの場合は、Auth0 DashboardNativeアプリケーションを設定し、DomainとClient IDを控えておきます。

ステップ2: 依存関係をインストールする

npm install @auth0/auth0-react @capacitor/browser @capacitor/app
npx cap sync

ステップ3: Auth0Providerをセットアップする

Capacitor向けに設定したAuth0Providerでアプリのルートをラップします。 src/main.tsxに以下を記述します:

import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const domain = import.meta.env.VITE_AUTH0_DOMAIN;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
const packageId = import.meta.env.VITE_AUTH0_PACKAGE_ID; // 例: com.example.myapp

const redirectUri = `${packageId}://${domain}/capacitor/${packageId}/callback`;

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      useRefreshTokens={true}
      useRefreshTokensFallback={false}
      authorizationParams={{
        redirect_uri: redirectUri
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);

ステップ4: Capacitor Browserを使ったログインを実装する

import { useAuth0 } from '@auth0/auth0-react';
import { Browser } from '@capacitor/browser';

const { loginWithRedirect } = useAuth0();

const login = async () => {
  await loginWithRedirect({
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};

ステップ5: ディープリンク経由でコールバックを処理する

import { useEffect } from 'react';
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { useAuth0 } from '@auth0/auth0-react';

const { handleRedirectCallback } = useAuth0();

useEffect(() => {
  const listener = CapApp.addListener('appUrlOpen', async ({ url }) => {
    if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
      await handleRedirectCallback(url);
    }
    await Browser.close();
  });

  return () => {
    listener.then(l => l.remove());
  };
}, [handleRedirectCallback]);

ステップ6: ログアウトを実装する

const doLogout = async () => {
  await logout({
    logoutParams: {
      returnTo: `${packageId}://${domain}/capacitor/${packageId}/callback`
    },
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};

ステップ7: ビルドしてテストする

Agentへの指示: 統合後、以下でビルドを確認してください:

ionic build
npx cap sync

iOS向け: npx cap open ios を実行後、Xcodeでビルドします。 Android向け: npx cap open android を実行後、Android Studioでビルドします。 ビルドが失敗した場合は、5〜6回繰り返して問題を修正してください。 それでも失敗する場合は、AskUserQuestionを使ってサポートを要請してください。

詳細ドキュメント

  • セットアップガイド — Auth0 CLIの設定、CapacitorのURLスキーム登録、シークレット管理
  • 統合パターン — Capacitor Browserを使ったログイン/ログアウト、ディープリンクコールバック処理、ユーザープロフィール、保護されたルート、トークンアクセス、エラーハンドリング
  • テストとリファレンス — Auth0Providerのprops、useAuth0フック、Capacitor pluginの設定に関する完全なAPIリファレンス、テストチェックリスト、よくある問題

よくある間違い

間違い 修正方法
Auth0 DashboardでアプリタイプがNativeに設定されていない Dashboardの設定でアプリケーションタイプを「Native」に変更する
コールバックURLの形式が欠落または不正 YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback の形式を使用し、完全に一致させること
リフレッシュトークンが有効化されていない Auth0Providerに useRefreshTokens={true}useRefreshTokensFallback={false} を設定する
@capacitor/browser または @capacitor/app が未インストール 両方をインストールする: npm install @capacitor/browser @capacitor/app && npx cap sync
ディープリンクコールバックが処理されていない CapApp.addListener('appUrlOpen', ...) を追加してAuth0リダイレクトを処理する
インストール後に npx cap sync を忘れる Capacitor pluginのインストール後は必ず npx cap sync を実行すること
リダイレクトURIに window.location.origin を使用している http://localhost ではなく、カスタムURLスキーム(packageId://domain/...)を使用すること
DashboardのAllowed Originsが未設定 Allowed Originsに capacitor://localhost, http://localhost を追加する
モバイルでlocalStorageが永続的に扱われている 信頼性の高いトークン永続化のためにリフレッシュトークンを使用する(useRefreshTokens={true}
iOS SSOが機能しない iOS 11以降、SFSafariViewControllerはSafariとCookieを共有しないため、これは仕様通りの動作
実機でテストしていない 認証フローは必ず実機でテストすること。シミュレータではディープリンクが正しく処理されない場合がある

WebAuthメソッドについて

このSDKは、Capacitor Browser pluginを通じてAuth0のUniversal Login(WebAuth)を使用します。 loginWithRedirect() メソッドは、Auth0の認可エンドポイントをシステムブラウザ (iOS上のSFSafariViewController、Android上のChrome Custom Tabs)で開きます。 認証後、Auth0はカスタムスキームを使ったネイティブコールバックURL {packageId}://{domain}/capacitor/{packageId}/callback を通じてアプリにリダイレクトします。 @capacitor/app pluginがこのディープリンクをキャプチャし、 handleRedirectCallback(url) が認可コードの交換処理を行います。

https://{domain}/android/{packageId}/callbackhttps://{domain}/ios/{bundleId}/callback を使用する標準のネイティブSDKとは異なり、Ionic CapacitorアプリはパッケージIDをURLスキームとして使用する Capacitor固有のコールバックパスを採用します。

関連スキル

  • auth0-react — React SPA(ブラウザのみ、Capacitorなし)
  • auth0-ionic-angular — IonicとAngularおよびCapacitor
  • auth0-ionic-vue — IonicとVueおよびCapacitor
  • auth0-react-native — React Native(bare CLI、Ionic/Capacitorなし)
  • auth0-expo — Expo(React Native)とAuth0

クイックリファレンス

API 説明
Auth0Provider コンテキストプロバイダー — Auth0設定でアプリのルートをラップする
useAuth0() フック — { isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback } を返す
loginWithRedirect({ openUrl }) Universal Login経由でログイン — openUrl コールバック内で Browser.open() を使用する
logout({ logoutParams, openUrl }) ログアウト — openUrl コールバック内で Browser.open() を使用する
handleRedirectCallback(url) ディープリンクから受け取ったAuth0コールバックURLを処理する
getAccessTokenSilently() アクセストークンを取得する(モバイルではリフレッシュトークンを使用)
withAuthenticationRequired(Component) ルートを保護するためのHOC
Browser.open({ url }) Capacitor — URLをシステムブラウザ(SFSafariViewController / Chrome Custom Tabs)で開く
CapApp.addListener('appUrlOpen', cb) Capacitor — ディープリンクイベントをリッスンする
Browser.close() Capacitor — コールバック後にアプリ内ブラウザを閉じる

参考リンク

原文(English)を表示

Auth0 Ionic React (Capacitor) Integration

Add Auth0 authentication to Ionic React applications using Capacitor. This skill covers native mobile authentication using the @auth0/auth0-react SDK combined with @capacitor/browser and @capacitor/app plugins for deep link handling on iOS and Android.

Prerequisites

  • Node.js 18+
  • Ionic CLI (npm install -g @ionic/cli)
  • An existing Ionic React application with Capacitor configured
  • Auth0 account and tenant
  • For iOS: Xcode 14+ and CocoaPods
  • For Android: Android Studio with API level 21+
  • Auth0 CLI — brew install auth0/auth0-cli/auth0

When NOT to Use

Use Case Recommended Skill
React SPA (no Capacitor/Ionic) auth0-react
React Native (bare CLI) auth0-react-native
Expo (React Native) auth0-expo
Ionic + Angular + Capacitor auth0-ionic-angular
Ionic + Vue + Capacitor auth0-ionic-vue
Next.js (server-side) auth0-nextjs
iOS native (Swift) auth0-swift
Android native (Kotlin) auth0-android

Quick Start Workflow

Step 1: Configure Auth0

For automated setup with Auth0 CLI, see Setup Guide for complete scripts.

For manual setup, configure a Native application in the Auth0 Dashboard and note your Domain and Client ID.

Step 2: Install Dependencies

npm install @auth0/auth0-react @capacitor/browser @capacitor/app
npx cap sync

Step 3: Set Up Auth0Provider

Wrap the app root with Auth0Provider, configuring it for Capacitor. In src/main.tsx:

import React from 'react';
import { createRoot } from 'react-dom/client';
import { Auth0Provider } from '@auth0/auth0-react';
import App from './App';

const domain = import.meta.env.VITE_AUTH0_DOMAIN;
const clientId = import.meta.env.VITE_AUTH0_CLIENT_ID;
const packageId = import.meta.env.VITE_AUTH0_PACKAGE_ID; // e.g., com.example.myapp

const redirectUri = `${packageId}://${domain}/capacitor/${packageId}/callback`;

createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      useRefreshTokens={true}
      useRefreshTokensFallback={false}
      authorizationParams={{
        redirect_uri: redirectUri
      }}
    >
      <App />
    </Auth0Provider>
  </React.StrictMode>
);

Step 4: Implement Login with Capacitor Browser

import { useAuth0 } from '@auth0/auth0-react';
import { Browser } from '@capacitor/browser';

const { loginWithRedirect } = useAuth0();

const login = async () => {
  await loginWithRedirect({
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};

Step 5: Handle Callback via Deep Link

import { useEffect } from 'react';
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { useAuth0 } from '@auth0/auth0-react';

const { handleRedirectCallback } = useAuth0();

useEffect(() => {
  const listener = CapApp.addListener('appUrlOpen', async ({ url }) => {
    if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
      await handleRedirectCallback(url);
    }
    await Browser.close();
  });

  return () => {
    listener.then(l => l.remove());
  };
}, [handleRedirectCallback]);

Step 6: Implement Logout

const doLogout = async () => {
  await logout({
    logoutParams: {
      returnTo: `${packageId}://${domain}/capacitor/${packageId}/callback`
    },
    async openUrl(url) {
      await Browser.open({ url, windowName: "_self" });
    }
  });
};

Step 7: Build and Test

Agent instruction: After integration, verify the build:

ionic build
npx cap sync

For iOS: npx cap open ios then build in Xcode. For Android: npx cap open android then build in Android Studio. If the build fails, iterate up to 5-6 times to fix issues. If still failing, use AskUserQuestion to request help.

Detailed Documentation

  • Setup Guide — Auth0 CLI configuration, Capacitor URL scheme registration, secret management
  • Integration Patterns — Login/logout with Capacitor Browser, deep link callback handling, user profile, protected routes, token access, error handling
  • Testing & Reference — Full API reference for Auth0Provider props, useAuth0 hook, Capacitor plugin configuration, testing checklist, common issues

Common Mistakes

Mistake Fix
App type not set to Native in Auth0 Dashboard Change application type to "Native" in Dashboard settings
Missing or incorrect callback URL format Use YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback — must match exactly
Not enabling refresh tokens Set useRefreshTokens={true} and useRefreshTokensFallback={false} on Auth0Provider
Missing @capacitor/browser or @capacitor/app Install both: npm install @capacitor/browser @capacitor/app && npx cap sync
Not handling deep link callback Add CapApp.addListener('appUrlOpen', ...) to process Auth0 redirect
Forgetting npx cap sync after install Always run npx cap sync after installing Capacitor plugins
Using window.location.origin as redirect URI Use the custom URL scheme (packageId://domain/...), not http://localhost
Missing Allowed Origins in Dashboard Add capacitor://localhost, http://localhost to Allowed Origins
localStorage treated as persistent on mobile Use refresh tokens (useRefreshTokens={true}) for reliable token persistence
iOS SSO not working SFSafariViewController doesn't share cookies with Safari on iOS 11+; this is expected
Not testing on physical device Always test auth flows on a physical device; simulators may not handle deep links correctly

WebAuth Method

This SDK uses Auth0's Universal Login (WebAuth) via the Capacitor Browser plugin. The loginWithRedirect() method opens the Auth0 authorization endpoint in a system browser (SFSafariViewController on iOS, Chrome Custom Tabs on Android). After authentication, Auth0 redirects back to the app using a native callback URL with a custom scheme: {packageId}://{domain}/capacitor/{packageId}/callback. The @capacitor/app plugin captures this deep link, and handleRedirectCallback(url) processes the authorization code exchange.

Unlike standard native SDKs that use https://{domain}/android/{packageId}/callback or https://{domain}/ios/{bundleId}/callback, Ionic Capacitor apps use the Capacitor-specific callback path with the package ID as the URL scheme.

Related Skills

  • auth0-react — React SPA (browser-only, no Capacitor)
  • auth0-ionic-angular — Ionic with Angular and Capacitor
  • auth0-ionic-vue — Ionic with Vue and Capacitor
  • auth0-react-native — React Native (bare CLI, no Ionic/Capacitor)
  • auth0-expo — Expo (React Native) with Auth0

Quick Reference

API Description
Auth0Provider Context provider — wraps app root with Auth0 config
useAuth0() Hook — returns { isLoading, isAuthenticated, user, loginWithRedirect, logout, getAccessTokenSilently, handleRedirectCallback }
loginWithRedirect({ openUrl }) Login via Universal Login — use Browser.open() in openUrl callback
logout({ logoutParams, openUrl }) Logout — use Browser.open() in openUrl callback
handleRedirectCallback(url) Process Auth0 callback URL from deep link
getAccessTokenSilently() Get access token (uses refresh tokens on mobile)
withAuthenticationRequired(Component) HOC to protect routes
Browser.open({ url }) Capacitor — opens URL in system browser (SFSafariViewController / Chrome Custom Tabs)
CapApp.addListener('appUrlOpen', cb) Capacitor — listens for deep link events
Browser.close() Capacitor — closes the in-app browser after callback

References

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。