> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# ユースケース: ネイティブからWebへのSSOを使用してモバイルからWebへの決済フローを設定する

> ネイティブからWebへのSSOとセッション転送トークンを使用して、iOS または Android アプリから Web アプリ内の安全で認証済みのサブスクリプションフローへ、ユーザーをシームレスに移行できます。

> [card] 始める前に
>
> 1. ネイティブアプリケーションと Web アプリケーションを登録・設定するための Auth0 テナントを作成します。
>
> 2. Auth0 テナント向けに [Auth0 CLI](https://github.com/auth0/auth0-cli) をインストールして設定します。
>
> 3. お使いのプラットフォームに対応する Quickstart を使って、ネイティブアプリケーションに Auth0 認証を追加します。
>
> * [iOS Swift Quickstart](/docs/docs/ja-jp/quickstart/native/ios-swift)
>
> * [Android Quickstart](/docs/docs/ja-jp/quickstart/native/android)
>
> 4. ネイティブアプリケーションに [refresh\_token](/docs/docs/ja-jp/secure/tokens/refresh-tokens/get-refresh-tokens) のサポートを追加します。
>
> 5. [React Single Page App Quickstart](/docs/docs/ja-jp/quickstart/spa/react) を使って、Web アプリケーションに Auth0 認証を追加します。

[Native to Web シングルサインオン (SSO)](/docs/docs/ja-jp/authenticate/single-sign-on/native-to-web) を使用すると、ネイティブアプリケーションと Web ベースの有料メンバーシップフローの間で、シームレスかつ安全なユーザー体験を実現できます。ネイティブからWebへのSSO (シングルサインオン (SSO): ユーザーが 1 つのアプリケーションにログインすると、他のアプリケーションにも自動的にログインできる仕組みです。) により、ネイティブアプリケーションは、有効期限の短い安全な `session_transfer_token` を使って、ユーザーの認証コンテキストを Web アプリケーションに送信できます。

以下のセクションでは、次の機能を追加する方法を説明します。

* ネイティブアプリケーションには、認証済みユーザーが安全な Web チェックアウト画面を通じて有料メンバーシッププランに登録できる「今すぐ登録」ボタン。
* Web アプリケーションには、ユーザーが再度ログインすることなくメンバーシップのサブスクリプションを選択できる「サブスクリプション」ページ。

このユースケースでは、Auth0 React SDK を使用する React ベースの Web アプリケーションに焦点を当てています。

Node や Express など別のフレームワークを使用している場合でも、URL パラメーターまたは Cookie を介して `session_transfer_token` を管理するロジックに応じて適宜対応できます。

## Auth0 CLI を設定する

[Auth0 CLI](https://github.com/auth0/auth0-cli) を使用して、Auth0 テナントを設定します。[Auth0 Management API](/docs/docs/ja-jp/api/management/v2) を使用することもできます。詳しくは、[ネイティブからWebへのSSOを設定する](/docs/docs/ja-jp/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web#configure-native-applications) を参照してください。

次の手順に従って、[Auth0 CLI](https://github.com/auth0/auth0-cli) を使用して Auth0 テナントに認証します。

1. Auth0 CLI を初期化する

```bash lines theme={null}
auth0 login
```

2. **As a user** を選択し、ログインフローに従います。

```bash lines theme={null}
How would you like to authenticate?
> As a user
  As a machine
```

3. ネイティブからWebへのSSOを有効にするAuth0 テナントを選択します。

## Auth0 を設定する

### ネイティブアプリケーションでネイティブからWebへのSSOを有効にする

ネイティブからWebへのSSOでは、ネイティブアプリケーションからWebアプリケーションへのSSOを確立するために `session_transfer_token` を使用します。`session_transfer_token` を使用すると、Auth0 はユーザー、元のネイティブアプリケーション、および追加のコンテキストを安全に識別できます。詳しくは、[Native to Web SSO](/docs/docs/ja-jp/authenticate/single-sign-on/native-to-web/configure-implement-native-to-web) をご覧ください。

Auth0 CLI を使用してネイティブからWebへのSSOを有効にします:

### WebアプリケーションでネイティブからWebへのSSOを有効にする

Auth0 CLIを使用して、CookieまたはURLパラメーター経由の認証で `session_transfer_token` を受け入れられるよう、Webアプリケーションを有効にします。

`session_transfer_token` が Cookie としてブラウザーに設定される場合、ウェブアプリケーション側で追加の変更を行う必要はありません。必要なのは、ユーザーを Auth0 テナントの `/authorize` エンドポイントにリダイレクトするために、ブラウザーが[アプリケーションの Login URI](/docs/docs/ja-jp/get-started/applications/application-settings#application-uris) に遷移することだけです。

Application Login URI は、Auth0 Dashboard のアプリケーション設定で構成できます。これは、外部ソースからログインが開始されたときに Auth0 がユーザーをリダイレクトする先のルートです。

## Webアプリケーションにサブスクリプションページを作成する

サブスクリプションページを作成するため、`/src/views/` に新しいファイルを追加します:

### ステップ 1: 新しいビューファイルを追加する

`src/views/JoinMembership.js` にファイルを作成します。このファイルでは、ユーザーに有料サブスクリプションの手続きを完了するよう求めます。

```js lines expandable theme={null}
import React, { useEffect } from "react";
import { useAuth0 } from "@auth0/auth0-react";
import { useLocation } from "react-router-dom";
import { Container, Button } from "reactstrap";
import Loading from "../components/Loading";

const JoinMembership = () => {
  const { isAuthenticated, isLoading, loginWithRedirect } = useAuth0();
  const location = useLocation();

  useEffect(() => {
    if (isLoading || isAuthenticated) return;

    const params = new URLSearchParams(location.search);
    const token = params.get("session_transfer_token");

    const redirectOptions = {
      appState: { returnTo: "/join-membership" },
      authorizationParams: {},
    };

    if (token) {
      redirectOptions.authorizationParams.session_transfer_token = token;
    }

    loginWithRedirect(redirectOptions);
  }, [isAuthenticated, isLoading, loginWithRedirect, location.search]);

  if (isLoading) {
    return <Loading />;
  }

  if (!isAuthenticated) {
    return <p>Redirecting to login...</p>;
  }

  return (
    <Container className="mt-5">
      <h1>Choose a Subscription Plan</h1>
      <Button color="primary" className="mb-3" onClick={() => alert("Subscribed to Basic!")}>
        Basic – $5/month
      </Button>
      <Button color="secondary" className="mb-3" onClick={() => alert("Subscribed to Pro!")}>
        Pro – $10/month
      </Button>
      <Button color="success" className="mb-3" onClick={() => alert("Subscribed to Premium!")}>
        Premium – $20/month
      </Button>
    </Container>
  );
};

export default JoinMembership;
```

### 手順 2: 新しいルートを追加する

`src/App.js` ファイルを編集し、新しいサブスクリプションページに `/join-membership` ルートを追加します。

```js lines theme={null}
import JoinMembership from "./views/JoinMembership";

 {/* メンバーシップ参加ページにリダイレクト */}
<Route path="/join-membership" component={JoinMembership} />
```

新しい `/join-membership` ルートでは、次の処理を行います。

* ユーザーが認証済みかどうかを判定します。認証されていない場合は、ユーザーを Universal Login (Universal Login: アプリケーションは、ユーザーの本人確認を行うために、Auth0 の認可サーバーでホストされている Universal Login にリダイレクトされます。) ページにリダイレクトします。
* `session_transfer_token` が URL パラメーターとして追加されている場合、その token は認証リクエストに渡されます。
* 認証が完了すると、ユーザーにはさまざまなメンバーシッププランに登録するためのボタンが表示されます。

> [!WARNING]
>
> React アプリを実行し、`http://localhost:3000/join-membership` にアクセスしてください。
>
> * ユーザーが認証済みの場合は、サブスクリプションのオプションが表示されます。
> * ユーザーが認証されていない場合は、自動的に Auth0 Universal Login ページにリダイレクトされます。
>
>   * URL に `session_transfer_token` が含まれている場合は、Auth0 へのログインリクエストにその token が含まれます。
>   * 含まれていない場合は、標準の Web 認証を使用してログインが続行されます。
>
> ユーザーがログインすると、サブスクリプションのオプションを選択するために `/join-membership` ページに戻ります。

## ネイティブアプリケーションを設定する

ネイティブアプリケーションでは、ウェブアプリケーションを起動する直前に、`refresh_token` を `session_transfer_token` に交換する必要があります。そのため、セッション転送のための交換処理とウェブアプリケーションを起動するロジックは、同じイベントハンドラー内 (たとえばボタンの `onClick` メソッド) に追加します。

### iOS

以下の手順では、iOSネイティブアプリケーションにモバイルからWebへの決済を追加する方法を説明します。

#### ステップ 1: `Subscribe to Membership` ボタンを追加する

iOS ネイティブアプリから Web ベースのサブスクリプション フローを開始するには、`ProfileView.swift` ファイルに `Subscribe to Membership` ボタンを追加します。

`ProfileView.swift` ファイルの body を編集し、ユーザー情報の下にボタンを追加します:

```swift lines theme={null}
import SwiftUI

struct ProfileView: View {
    let user: User
    var onSubscribe: () -> Void = {}

    var body: some View {
        List {
            Section(header: ProfileHeader(picture: user.picture)) {
                ProfileCell(key: "ID", value: user.id)
                ProfileCell(key: "Name", value: user.name)
                ProfileCell(key: "Email", value: user.email)
                ProfileCell(key: "Email verified?", value: user.emailVerified)
                ProfileCell(key: "Updated at", value: user.updatedAt)
            }

            Section {
                Button("Subscribe to Membership", action: onSubscribe)
            }
        }
    }
}
```

`ProfileView.swift` ファイルでは、`Subscribe to Membership` ボタンを追加し、選択時の動作を `onSubscribe` クロージャで決定します。

#### ステップ 2: ネイティブからWebへのSSOを使ってサブスクリプション フローを実装する

`Subscribe to Membership` ボタンの動作を定義するには、`MainView.swift` ファイルを編集します。

このサンプルでは、説明のために audience `https://sample.api.com` を使用しています。この識別子を持つ API を Auth0 テナントに作成することも、ご自身の API の識別子に置き換えることもできます。

詳しくは、[Set Up APIs](/docs/docs/ja-jp/get-started/auth0-overview/set-up-apis)をご覧ください。

これにより、ユーザーはネイティブアプリで `Subscribe to Membership` を選択し、再度ログインすることなく、すぐに Web アプリケーションでのサブスクリプション手続きを開始できます。

### Android

以下の手順では、Androidネイティブアプリケーションにモバイルからウェブへの決済を追加する方法を説明します。

#### ステップ 1: メインページにSubscribeボタンを追加する

AndroidネイティブアプリケーションからWebベースのサブスクリプション フローを起動するには、UIに`Subscribe to Membership`ボタンを追加します。

`MainActivity.kt`ファイルを編集し、`onCreate()`メソッドに次のコードを追加します。

```kotlin wrap lines theme={null}
binding.buttonSubscribe.setOnClickListener { launchSubscriptionFlow() }
```

`activity_main.xml` ファイルを編集し、`@+id/button_patch_metadata` ボタンの後に以下のコードを追加します:

```xml lines theme={null}
<Button
    android:id="@+id/buttonSubscribe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Subscribe to Membership" />
```

#### ステップ 2: ネイティブからWebへのSSOを使用してサブスクリプションフローを実装する

`Subscribe to Membership` ボタンの動作を定義するため、`MainActivity.kt` ファイルを編集します。

1. ログインフローを拡張し、サブスクリプション操作を処理します。

```kotlin lines theme={null}
// 必要なインポート
import com.auth0.android.authentication.storage.SecureCredentialsManager
import com.auth0.android.authentication.storage.SharedPreferencesStorage
import com.auth0.android.result.SSOCredentials
```

2. `onCreate()`メソッドに`credentialsManager:`を追加するよう更新します

```kotlin lines theme={null}
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Auth0 アプリケーションの詳細を使用してアカウントオブジェクトをセットアップする
        account =  Auth0.getInstance(
            getString(R.string.com_auth0_client_id),
            getString(R.string.com_auth0_domain)
        )

        // ボタンのクリックイベントをログインアクションに紐付ける
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.buttonLogin.setOnClickListener { loginWithBrowser() }
        binding.buttonLogout.setOnClickListener { logout() }
        binding.buttonGetMetadata.setOnClickListener { getUserMetadata() }
        binding.buttonPatchMetadata.setOnClickListener { patchUserMetadata() }
        binding.buttonSubscribe.setOnClickListener { launchSubscriptionFlow() }

        secureCredentialsManager = SecureCredentialsManager(
            this,
            AuthenticationAPIClient(account),
            SharedPreferencesStorage(this)
        )

    }
```

3. `loginwithBrowser()` メソッドを更新し、`credentialsManager:` を使用して資格情報を保存するようにします

```kotlin lines theme={null}
private fun loginWithBrowser() {
    WebAuthProvider.login(account)
        .withScheme(getString(R.string.com_auth0_scheme))
        .withScope("openid profile email offline_access")
        .withAudience("https://example.api.com")
        .start(this, object : Callback<Credentials, AuthenticationException> {
            override fun onSuccess(credentials: Credentials) {
                secureCredentialsManager.saveCredentials(credentials)
                cachedCredentials = credentials
                showSnackBar("Success: ${credentials.accessToken}")
                updateUI()
                showUserProfile()
            }

            override fun onFailure(exception: AuthenticationException) {
                showSnackBar("Failure: ${exception.getCode()}")
            }
        })
}
```

このサンプルでは、説明のために audience `https://sample.api.com` を使用しています。Auth0 テナントでこの識別子を持つ API を作成することも、ご自身の API 識別子に置き換えることもできます。

詳しくは、[Set Up APIs](/docs/docs/ja-jp/get-started/auth0-overview/set-up-apis) を参照してください。

4. Web アプリケーションを開くには、`launchSubscriptionFlow()` メソッドを追加します:

```kotlin lines expandable theme={null}
private fun launchSubscriptionFlow() {
    secureCredentialsManager.getSsoCredentials(
        mapOf(),  // オプションのパラメーター
        object : Callback<SSOCredentials, CredentialsManagerException> {
            override fun onSuccess(result: SSOCredentials) {
                val sessionToken = result.sessionTransferToken

                val cookieValue =
                    "auth0_session_transfer_token=$sessionToken; Path=/; Secure; HttpOnly; SameSite=None"
                val cookieManager = android.webkit.CookieManager.getInstance()
                cookieManager.setAcceptCookie(true)
                cookieManager.setCookie("https://${getString(R.string.com_auth0_domain)}", cookieValue)

                val webView = android.webkit.WebView(this@MainActivity)
                webView.settings.javaScriptEnabled = true
                webView.webViewClient = object : android.webkit.WebViewClient() {
                    override fun shouldOverrideUrlLoading(view: android.webkit.WebView?, url: String?) = false
                }

                webView.loadUrl("http://localhost:3000/join-membership")
                setContentView(webView)
            }

            override fun onFailure(error: CredentialsManagerException) {
                showSnackBar("Failed to get session transfer token: ${error.message}")
            }
        }
    )
}
```

これにより、ユーザーはネイティブアプリで `Subscribe to Membership` を選択するだけで、再度ログインすることなく、すぐに Web アプリでの登録手続きを開始できます。

## ネイティブからWebへのSSOの実装をテストする

すべての設定が完了したら、iOS または Android のネイティブアプリケーションを起動してログインし、プロファイルまたはメイン画面に移動して、**Subscribe to Membership**ボタンを選択します。

次のことが行われます。

* 保存されている `refresh_token` を使用して、安全な `session_transfer_token` を取得します
* `session_transfer_token` が Auth0ドメインの Cookie に設定されます
* `WKWebView` を使用して、Webアプリケーションの `/join-membership` ルートを読み込みます
* Webアプリケーションが `session_transfer_token` を受け取り、ネイティブからWebへのSSO を使用してログインを完了します
* ユーザーには、Webアプリケーションですぐに登録オプションが表示されます

これにより、モバイルのネイティブアプリケーションのユーザーは、再度ログインを求められることなく、Webアプリケーションで安全な認証済みフローを開始できるシームレスな体験を実現できます。

## 次のステップ

* ネイティブからWebへのSSOの設定オプションをさらに確認する:セッションの有効期間、リフレッシュトークン (リフレッシュトークン: ユーザーに再度ログインさせることなく、新しいアクセストークンを取得するために使用されるトークン。)のローテーション、デバイスバインディング、カスケード失効について、[ネイティブからWebへのSSOのドキュメント](/docs/docs/ja-jp/authenticate/single-sign-on/native-to-web)で詳しく確認してください。
* Progressive Profilingでpost-loginエクスペリエンスをカスタマイズする:Auth0の[Progressive Profile Form](/docs/docs/ja-jp/customize/forms/configure-progressive-profile-form)を使用して、ログイン後に追加のユーザーデータ (プランの希望、住所、支払いの意向など) を収集し、サブスクリプションオプションを表示する前に活用できます。
