2026年8月4日火曜日

Oracle Backend for Firebaseを組み込んだアプリケーションをGoogleアカウントで認証する

Oracle Backend for Firebase(Fusabase)は、Google、Facebook、GitHubといったソーシャル・ログイン(Social login)および、外部IDプロバイダーによるログイン(OpenID Connect)をサポートしています。

本記事では、Fusabase SDKに含まれるAuthenticationモジュールをアプリケーションに組み込み、Social loginとして提供されているGoogleを構成して、アプリケーションのユーザー認証を行なってみます。


Authentication typeを構成することにより、外部のプロバイダーを使用したユーザー認証を実装することもできます。こちらの構成については、また別の機会に確認したいと思います。

注) Authentication typeにAdvancedを選択し、IDCSとしてOracle IAMを構成する場合、IAMの機能としてEnd-user self-registrationが必要です。Oracle IAMのIdentity Domain TypeがFreeだと、End-user self-registrationはサポートされていません(IAM Identity Domain Typesの表を参照)。そのため、Oracle Backend for Firebaseの組み込みの認証タイプ(BASIC)を変更し、AdvancedIDCSとしてOracle IAMを構成するには、有料のサブスクリプションが必要になります。

Googleによるユーザー認証を組み込むアプリケーションとして、以下のLiveLabsを実施して作成したアプリケーションを使用します。


Googleプロバイダを構成する



最初にリダイレクトURIを確認します。

Oracle Backend for Firebaseのコンソールにサインインし、AuthenticationSocial loginを開きます。

GoogleActionを実行します。


プロバイダをEnableに切り替えます。Enableにすると、リダイレクトURIが表示されます。なぜかCopy URIボタンが効かない(サイトをHTTPで構成しているからかもしれません)ため、表示されているリダイレクトURIを選択して、クリップボードにコピーします。

Client IdおよびClient Secretは、Googleに認証情報を作成することにより得られる値なので現時点では不明です。キャンセルをクリックし、ドロワーを閉じます。


Google Cloudのコンソールでの作業に移ります。

プロジェクトが作成されていることを前提とします。

APIとサービス認証情報を開きます。


認証情報の作成から、OAuthクライアントIDを選択します。


Google Auth Platformクライアントの作成に移ります。

アプリケーションの種類としてウェブアプリケーションを選択します。名前fusabaseとしました。

承認済みのリダイレクトURIとして、先ほどOracle Backend for Firebaseのコンソールで確認したリダイレクトURIを設定します。

以上で作成します。


OAuthクライアントが作成されます。クライアントIDクライアントシークレットが表示されるので、これらをコピーします。JSONをダウンロードしておくのも良いでしょう。

OKをクリックしてダイアログを閉じます。


OAuthクライアントとしてfusabaseが作成されます。


Oracle Backend for Firebaseのコンソールに戻り、Authenticationを開きます。

Social loginGoogleの設定を更新します。Googleに作成したOAuthクライアントfusabaseのクライアントIDクライアントシークレットを設定します。

プロバイダーをEnableにし、Saveします。


以上で、Googleアカウントによるソーシャル・ログインが有効になりました。


Web/JavaScriptアプリケーションを認証する



JavaScript SDKのAuthenticationモジュールの説明は、以下に記載されています。

LiveLabsのBuild a Recipe Web App with Oracle Backend for Firebaseを実施して作成されたアプリケーションを元に作業します。

Sign inボタンをクリックすると表示されるパネルのSign inCreate accountの間に、Sign in with Googleというボタンを追加します。


index.htmlsignInButtonの下に、以下の一行を挿入します。ページに表示されるボタンとして、Sign in with Googleが追加されます。

<button id="signInWithGoogleButton" class="btn btn-outline" type="button">Sign in with Google</button>


scripts/app.jsの先頭にあるimport文を更新します。fusabase/authより追加で、GoogleAuthProvidersignInWithPopupをインポートします。
import {
  GoogleAuthProvider,
  signInWithPopup,
  createUserWithEmailAndPassword,
  getAuth,
  onAuthStateChanged,
  signInWithEmailAndPassword,
  signOut
} from "fusabase/auth";
ボタンsignInWithGoogleを、オブジェクトelの属性として含めます。

signInButtonの下に、以下の一行を挿入します。

signInWithGoogleButton: document.querySelector("#signInWithGoogleButton"),


ボタンsignInWithGoogleButtonをクリックしたときに実行されるコードを追加します。見つけやすいように、signInButtonのイベントリスナー定義の下の配置します。
  el.signInWithGoogleButton.addEventListener("click", () => {
    runAction("Signed in with Google.", async () => {
      // ── Sign in with Google ─────────
      await signInWithPopup(auth, new GoogleAuthProvider());
    });
  });

以上でアプリケーションの更新は完了です。

RecipeShareのアプリケーションにアクセスし、Sign In with Googleを実行します。


Googleでログインの画面がポップアップします。ログインするGoogleアカウントを選択します。


アプリケーション名として表示されているRecipeShareは、Google Auth Platformブランディングで設定しています。


Googleアカウントでのサインインに成功すると、メール・アドレスが表示されます。


以上で、Web/JavaScriptアプリケーションを、Googleアカウントで認証することができました。


iOS/Swiftアプリケーションを認証する



iOS SDKのAuthenticationモジュールの説明は、以下に記載されています。

LiveLabsのBuild a Recipe iOS App with Oracle Backend for Firebaseを実施して作成されたアプリケーションを元に作業します。

Services/AuthService.swiftに、GoogleアカウントでサインインするファンクションsignInWithGoogleを追加します。ファンクションsignInの下に配置します。
    /// Sign in with Google
    func signInWithGoogle() async throws {
        isLoading = true
        errorMessage = nil
        defer { isLoading = false }

        do {
            _ = try await FusabaseAuth.auth().signIn(with: GoogleAuthProvider())
        } catch {
            errorMessage = error.localizedDescription
            throw error
        }
    }

Views/AuthView.swiftに、追加したファンクションsignInWithGoogleを呼び出すボタンSign In With Googleを追加します。

AuthView.swiftの末尾に、アクションとしてsignInWithGoogleを追加します。
    // MARK: - Actions

    private func signInWithGoogle() {
        Task {
            do {
                try await authService.signInWithGoogle()
            } catch {
                // AuthService surfaces the message via `errorMessage`; nothing else to do.
            }
        }
    }

アクションsignInWithGoogleを呼び出すボタンを追加します。sign-upとsign-inを切り替えるボタン(表示はリンク)の下に配置します。
            // Sign In With Google
            Button(action: signInWithGoogle) {
                HStack {
                    if authService.isLoading {
                        ProgressView()
                            .controlSize(.small)
                            .padding(.trailing, 4)
                    }
                    Text("Sign In with Google")
                        .fontWeight(.semibold)
                        .frame(maxWidth: .infinity)
                }
            }
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .disabled(authService.isLoading)

以上でアプリケーションの更新は完了です。

RecipeShareのアプリケーションを実行します。Sign In with Googleのボタンが追加されています。

Sign In with Googleをクリックします。


Googleでログインの画面が表示されます。Googleアカウントを入力し、Enterを送信します。


Googleアカウントの構成によると思いますが、色々な方法で本人確認を求められます。


RecipeShareに再ログインしようとしています。と表示されたので次へ進みます。


Googleアカウントのサインインに成功し、登録されているレシピの一覧が表示されます。


以上で、iOS/Swiftアプリケーションを、Googleアカウントで認証することができました。


Android/Javaアプリケーションを認証する



Android SDKのAuthenticationモジュールの説明は、以下に記載されています。

LiveLabsのTitle Build a Recipe Android App with Oracle Backend for Firebaseを実施して作成されたアプリケーションを元に作業します。

Fusabase Android SDKの説明には記載されていませんが、Fusabase Android SDKのAuthenticationモジュールには、startActivityForSignInWithProviderが含まれています。このメソッドを使って、Googleアカウントによるサインインを実装します。

掲載しているほとんどのコードは、Claude Opus 5に生成させています。

AuthRepository.javaに以下の2つのファンクションを追加します。
    /**
     * Signs in with Google. The SDK opens a Custom Tab for the OAuth flow, so an
     * Activity is required. The result arrives through the auth state listener
     * once the browser redirects back to SocialLoginActivity.
     */
    public void signInWithGoogle(Activity activity) {
        isLoading.setValue(true);
        errorMessage.setValue(null);
        auth.startActivityForSignInWithProvider(activity, new GoogleAuthProvider(auth))
                .addOnSuccessListener(result -> isLoading.postValue(false))
                .addOnFailureListener(error -> {
                    isLoading.postValue(false);
                    errorMessage.postValue(error.getMessage());
                });
    }

    public void resumePendingSocialLogin() {
        Task<AuthResult> pending = auth.getPendingAuthResult();
        if (pending == null) {
            isLoading.postValue(false);
            return;
        }
        pending.addOnSuccessListener(result -> isLoading.postValue(false))
                .addOnFailureListener(error -> {
                    isLoading.postValue(false);
                    errorMessage.postValue(error.getMessage());
                });
    }

これらのファンクションが使用しているクラスをインポートするように、ファイルの先頭に以下のインポート文を追加します。
/* Sign in with Google */
import android.app.Activity;
import com.oracle.mobile.fusabase.auth.GoogleAuthProvider;
import com.oracle.mobile.fusabase.task.Task;
import com.oracle.mobile.fusabase.auth.AuthResult;

本家のFirebase Authentication SDKでは、startActivityForSignInWithProvider() は主に OAuthProvider(Apple、GitHub、Microsoft、OIDC など)の認証で使用するAPIとして紹介されています。Googleアカウントによるサインインについては、現在のFirebase公式ドキュメントでは Credential Manager を使用する方法が推奨されています。

Oracle Backend for Firebase (Fusabase) は、Oracle Databaseのクライアント・アプリケーションを作成する際に、Firebaseの開発体験を提供するSDKです。作成するアプリケーションは、あくまでOracle Databaseのクライアント・アプリケーションなので、ユーザー認証もエンタープライズ向けのOpenID Connectによる認証が主になるでしょう。そのため、Googleアカウントによる認証もCredential Managerを使わずに実装しました。

サインインの画面にボタンSign in with Googleを追加します。

res/values/strings.xmlに以下の1行を挿入します。ボタンのラベルとなる文字列です。

<string name="auth_button_google">Sign in with Google</string>


サインインの画面にボタンSign in with Googleを追加します。

res/layout/fragment_auth.xmlを開き、以下の要素をボタンSign inの下に配置します。
        <com.google.android.material.button.MaterialButton
            android:id="@+id/googleButton"
            style="@style/Widget.Material3.Button.OutlinedButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/spacing_sm"
            android:text="@string/auth_button_google" />

AuthFragment.javaを開き、ボタンのアクション(クリック)とAuthRepository.javaに記載したファンクションの紐付けを行います。

ボタンSign in with Google(googleButton)をクリックしたときに、ファンクションsignInWithGoogleが呼び出されるように、以下のコードを追加します。
        binding.googleButton.setOnClickListener(v -> {
            binding.errorText.setVisibility(View.GONE);
            App.get().auth().signInWithGoogle(requireActivity());
        });
他のボタンと同様に、ページのロード中はクリックを無効にします。以下の1行を、App.get().auth().getIsLoading().observe内に含めます。

binding.googleButton.setEnabled(!active);


resumePendingSocialLoginを呼び出すコードを、AuthFragment.javaの末尾に追加します。
    @Override
    public void onResume() {
        super.onResume();
        App.get().auth().resumePendingSocialLogin();
    }

main/AndroidManifest.xmlに記載されているSocialLoginActivityの設定を更新します。

android:launchMode="singleTop"を追加し、android:schemeとして、baasmobileで始まるapp_id(英子文字)を文字列として与えます。以下はandroid:schemeの例です。app_idは、作成したアプリケーションごとに異なります。

baasmobile581fb7467326f5b9e063020012ac0157
        <activity
            android:name="com.oracle.mobile.fusabase.auth.SocialLoginActivity"
            android:exported="true"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="baasmobile581fb7467326f5b9e063020012ac0157" />
            </intent-filter>
        </activity>


Googleアカウントによるユーザー認証の実装については以上で完了です。

Androidシミュレータを使って動作確認をするにあたって、ords_hostに10.0.2.2として仮想ネットワークを設定していると、Googleアカウントによるユーザー認証ができません。コールバック・アドレスはHTTPSで保護されているかlocalhostである必要があります。

そのため、main/fusabase-config.jsonords_hostでのホスト指定を、10.0.2.2からlocalhostに戻します。


AndroidシミュレータからORDSに直接接続する代わりに、adb - Android Debug Bridgeを使ってホスト上のTCPポート8181を、シミュレータから見たlocalhost:8181に割り当てます。

~/Library/Android/sdk/platform-tools/adb reverse tcp:8181 tcp:8181
~/Library/Android/sdk/platform-tools/adb reverse --list

adbへのパスは、Android Studioをインストールした環境によって、異なる可能性があります。

% ~/Library/Android/sdk/platform-tools/adb reverse tcp:8181 tcp:8181

% ~/Library/Android/sdk/platform-tools/adb reverse --list

host-10 tcp:8181 tcp:8181


% 


以上で、すべての設定が完了しました。

RecipeShareのアプリケーションを実行します。Sign in with Googleのボタンが追加されています。

Sign in with Googleをクリックします。


アカウントの選択画面に移ります。すでにサインインしたことのあるアカウントを選択するか、Use another accountを選択して、新たにサインインするユーザーを指定します。


アカウントの設定に応じた本人確認の手順が要求されます。

最終的にGoogleアカウントによる認証が成功すると、登録されているレシピの一覧が表示されます。


以上で、Android/Javaアプリケーションを、Googleアカウントで認証することができました。