メインコンテンツへスキップ

始める前に

  1. ネイティブアプリケーションと Web アプリケーションを登録して設定するための Auth0 テナントを作成します。
  2. Auth0 テナント用に Auth0 CLI をインストールして設定します。
  3. プラットフォームに応じた Quickstart を使用して、ネイティブアプリケーションに Auth0 Authentication を追加します。
  1. ネイティブアプリケーションに refresh_token のサポートを追加します。
  2. React Single Page App Quickstart を使用して、Web アプリケーションに Auth0 Authentication を追加します。
Native to Web Single Sign-On (SSO) を使用すると、ネイティブアプリケーションと Web ベースの有料会員登録フローの間で、シームレスかつ安全なユーザー体験を実現できます。Native to Web を使用すると、ネイティブアプリケーションは短時間のみ有効な安全な session_transfer_token を使って、ユーザーの認証コンテキストを Web アプリケーションに送信できます。 以下のセクションでは、次の追加方法について説明します。
  • ネイティブアプリケーションに、認証済みユーザーが安全な Web チェックアウト画面を通じて有料会員プランに登録できる Subscribe Now ボタン。
  • Web アプリケーションに、ユーザーが再度ログインすることなく会員プランを選択できる Subscription ページ。
このユースケースでは、Auth0 React SDK を使用する React ベースの Web アプリケーションを対象としています。Node や Express などの別のフレームワークを使用している場合でも、URL パラメーターまたは Cookie を介して session_transfer_token を管理するロジックは、それに合わせて応用できます。

Auth0 CLI を設定する

Auth0 CLI を使用して、Auth0 テナントを設定します。Auth0 Management API を使用することもできます。詳しくは、ネイティブから Web への SSO を設定する を参照してください。
Auth0 CLI を使用して Auth0 テナントに認証するには、次の手順に従います。
  1. Auth0 CLI を初期化する
auth0 login
  1. As a user を選択し、ログインフローに従ってください。
How would you like to authenticate?
> As a user
  As a machine
  1. Native to Web SSO を有効にする Auth0 テナントを選択します。

Auth0を設定する

ネイティブアプリケーションで Native to Web SSO を有効にする

Native to Web SSO では、session_transfer_token を使用して、ネイティブアプリケーションから Web アプリケーションへの SSO を確立します。session_transfer_token を使用すると、Auth0 はユーザー、送信元のネイティブアプリケーション、および追加のコンテキストを安全に識別できます。詳細については、Native to Web SSO を参照してください。 Auth0 CLI を使用して Native to Web SSO を有効にします。

Web アプリケーションで Native to Web SSO を有効にする

Auth0 CLI を使用して、Cookie または URL パラメーター経由で session_transfer_token を認証に利用できるよう、Web アプリケーションを有効にします。 session_transfer_token が Cookie を介してブラウザーに注入される場合、Web アプリケーションに追加の変更は必要ありません。必要なのは、ブラウザーが、ユーザーを Auth0 テナントの /authorize エンドポイントにリダイレクトする処理を行うために、アプリケーションの Login URI に移動することだけです。
Application Login URI は、Auth0 Dashboard のアプリケーション設定で構成できます。これは、外部ソースからログインを開始する際に、Auth0 がユーザーをリダイレクトする先のルートです。

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

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

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

src/views/JoinMembership.js にファイルを作成します。このファイルでは、ユーザーに有料サブスクリプションを完了するよう促します。
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 ルートを追加します。
import JoinMembership from "./views/JoinMembership";

 {/* メンバーシップ参加ページにリダイレクト */}
<Route path="/join-membership" component={JoinMembership} />
新しい /join-membership ルート:
  • ユーザーが認証済みかどうかを判定します。認証されていない場合は、ユーザーを ページにリダイレクトします。
  • URL パラメーターとして session_transfer_token が追加されている場合、そのトークンは認証リクエストに渡されます。
  • 認証後、ユーザーには異なるメンバーシッププランに登録するためのボタンが表示されます。
React アプリを実行し、http://localhost:3000/join-membership にアクセスします
  • ユーザーが認証済みの場合、サブスクリプションのオプションが表示されます。
  • ユーザーが認証されていない場合は、自動的に Auth0 Universal Login ページにリダイレクトされます。
    • URL に session_transfer_token が含まれている場合は、Auth0 へのログインリクエストにそのトークンが含まれます。
    • 含まれていない場合は、標準の Web 認証を使用してログインが行われます。
ユーザーがログインすると、サブスクリプションのオプションを選択するために /join-membership ページに戻ります。

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

ネイティブアプリケーションでは、Webアプリケーションを起動する直前に、refresh_tokensession_transfer_token に交換する必要があります。そのため、セッショントランスファーの交換処理と Webアプリケーションを起動するロジックは、同じイベントハンドラー内に追加してください。たとえば、ボタンの onClick メソッド内です。

iOS

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

ステップ 1: メンバーシップ登録ボタンを追加する

iOSネイティブアプリからWebベースのサブスクリプションフローを開始するには、ProfileView.swift ファイルに Subscribe to Membership ボタンを追加します。 ProfileView.swift ファイルの body を編集し、ユーザー情報の下にボタンを追加します:
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: Native to Web SSO を使用してサブスクリプションフローを実装する

MainView.swift ファイルを編集し、Subscribe to Membership ボタンの動作を定義します。
このサンプルでは、説明用にオーディエンス https://sample.api.com を使用しています。この識別子を持つ API を Auth0 テナントに作成することも、独自の API 識別子に置き換えることもできます。詳細については、Set Up APIs を参照してください。
これにより、ユーザーはネイティブアプリで Subscribe to Membership を選択し、再度ログインすることなく、すぐに Web アプリケーションでのサブスクリプション手続きを開始できます。

Android

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

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

Android ネイティブアプリケーションから Web ベースのサブスクリプションフローを開始するには、UI に Subscribe to Membership ボタンを追加します。 MainActivity.kt ファイルを編集し、onCreate() メソッドに次のコードを追加します。
binding.buttonSubscribe.setOnClickListener { launchSubscriptionFlow() }
activity_main.xml ファイルを編集し、@+id/button_patch_metadata ボタンの後に次のコードを追加します。
<Button
    android:id="@+id/buttonSubscribe"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Subscribe to Membership" />

ステップ 2: Native to Web SSO を使用してサブスクリプションフローを実装する

MainActivity.kt ファイルを編集して、Subscribe to Membership ボタンの動作を定義します。
  1. ログインフローを拡張し、サブスクリプション処理を実装します。
// 必要なインポート
import com.auth0.android.authentication.storage.SecureCredentialsManager
import com.auth0.android.authentication.storage.SharedPreferencesStorage
import com.auth0.android.result.SSOCredentials
  1. credentialsManager: を含めるように onCreate() メソッドを更新します
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)
        )

    }
  1. loginwithBrowser() メソッドを更新し、credentialsManager: を使用して認証情報を保存するようにします
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()}")
            }
        })
}
このサンプルでは、説明のためにオーディエンス https://sample.api.com を使用しています。Auth0 テナントでこの識別子を持つ API を作成することも、ご自身の API 識別子に置き換えることもできます。詳細については、Set Up APIs を参照してください。
  1. Web アプリケーションを開くには、launchSubscriptionFlow() メソッドを追加します。
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 アプリケーションのサブスクリプション手続きを開始できます。

Native to Web SSO の実装をテストする

すべての設定が完了したら、iOS または Android のネイティブアプリケーションを実行してログインし、Profile または Mainscreen に移動して Subscribe to Membership ボタンを選択します。 次の処理が実行されます。
  • 保存されている refresh_token を使用して、安全な session_transfer_token をリクエストします
  • session_transfer_token が Auth0 ドメイン用の cookie に設定されます
  • WKWebView を使用して、Web アプリケーションの /join-membership ルートを読み込みます
  • Web アプリケーションが session_transfer_token を受け取り、Native to Web SSO を使用してログインを完了します
  • ユーザーには、Web アプリケーションですぐにサブスクリプションオプションが表示されます
これにより、モバイルネイティブアプリケーションのユーザーは、再度ログインを求められることなく、Web アプリケーションで安全な認証済みフローを開始できるシームレスな体験を実現できます。

次のステップ

  • Native to Web SSO の設定オプションをさらに詳しく見る:セッションの有効期間、のローテーション、デバイスバインディング、カスケード失効について、Native to Web SSO ドキュメントで詳しく確認してください。
  • Progressive Profiling でログイン後のエクスペリエンスをカスタマイズする:Auth0 の Progressive Profile Form を使用して、ログイン後にプランの希望、住所、支払いの意向などの追加のユーザーデータを収集し、サブスクリプションの選択肢を表示する前に必要な情報を取得します。