Android で Google を使用して認証する

ユーザーが Google アカウントを使用して Firebase で認証することができます。

始める前に

  1. まだ追加していない場合は、Firebase を Android プロジェクトに追加します

  2. モジュール(アプリレベル)の Gradle ファイル(通常は <project>/<app-module>/build.gradle.kts または <project>/<app-module>/build.gradle)に、Android 用 Firebase Authentication ライブラリの依存関係を追加します。ライブラリのバージョニングの制御には、Firebase Android BoM を使用することをおすすめします。

    また、Firebase Authentication の設定の一環として、認証情報マネージャー SDK をアプリに追加する必要があります。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.9.0"))
    
        // Add the dependency for the Firebase Authentication library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth")
    // Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")
    }

    Firebase Android BoM を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。

    Firebase BoM を使用しない場合は、依存関係の行でそれぞれの Firebase ライブラリのバージョンを指定する必要があります。

    アプリで複数の Firebase ライブラリを使用する場合は、すべてのバージョンの互換性を確保するため、BoM を使用してライブラリのバージョンを管理することを強くおすすめします。

    dependencies {
        // Add the dependency for the Firebase Authentication library
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-auth:23.2.0")
    // Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")
    }
    Kotlin 固有のライブラリ モジュールをお探しの場合、 2023 年 10 月(Firebase BoM 32.5.0)以降、Kotlin と Java のどちらのデベロッパーもメイン ライブラリ モジュールを利用できるようになります(詳しくは、このイニシアチブに関するよくある質問をご覧ください)。

  3. アプリの SHA フィンガープリントを指定していない場合は、Firebase コンソールの [プロジェクトの設定] ページで指定します。 アプリの SHA フィンガープリントを取得する方法の詳細については、クライアントの認証をご覧ください。

  4. Firebase コンソールで、ログイン方法として Google を有効にします。
    1. Firebase コンソールで [Auth] セクションを開きます。
    2. [Sign-in method] タブで [Google] を有効にし、[保存] をクリックします。
  5. コンソールでプロンプトが表示されたら、更新された Firebase 構成ファイル(google-services.json)をダウンロードします。このファイルには、Google ログインに必要な OAuth クライアント情報が含まれています。

  6. この最新の構成ファイルを Android Studio プロジェクトに移動し、対応する古い構成ファイルを置き換えますAndroid プロジェクトに Firebase を追加するをご覧ください)。

Firebase で認証する

  1. 認証情報マネージャーのドキュメントの手順に沿って、「Google でログイン」をアプリに統合します。手順の概要は次のとおりです。
    1. GetGoogleIdOption を使用して Google ログイン リクエストをインスタンス化します。次に、GetCredentialRequest を使用して認証情報マネージャー リクエストを作成します。
      KotlinJava
      // Instantiate a Google sign-in request
      val googleIdOption = GetGoogleIdOption.Builder()
          // Your server's client ID, not your Android client ID.
          .setServerClientId(getString(R.string.default_web_client_id))
          // Only show accounts previously used to sign in.
          .setFilterByAuthorizedAccounts(true)
          .build()
      
      // Create the Credential Manager request
      val request = GetCredentialRequest.Builder()
          .addCredentialOption(googleIdOption)
          .build()
      // Instantiate a Google sign-in request
      GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()
              .setFilterByAuthorizedAccounts(true)
              .setServerClientId(getString(R.string.default_web_client_id))
              .build();
      
      // Create the Credential Manager request
      GetCredentialRequest request = new GetCredentialRequest.Builder()
              .addCredentialOption(googleIdOption)
              .build();

      上記のリクエストでは、「サーバー」のクライアント ID を setServerClientId メソッドに渡す必要があります。OAuth 2.0 クライアント ID を 確認するには:

      1. Google Cloud コンソールの [認証情報] ページを開きます。
      2. ウェブ アプリケーション タイプのクライアント ID がバックエンド サーバーの OAuth 2.0 クライアント ID です。
    2. Google ログインを統合した後、ログイン アクティビティに次のようなコードが追加されていることを確認します。
      KotlinJava
      private fun handleSignIn(credential: Credential) {
          // Check if credential is of type Google ID
          if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
              // Create Google ID Token
              val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
      
              // Sign in to Firebase with using the token
              firebaseAuthWithGoogle(googleIdTokenCredential.idToken)
          } else {
              Log.w(TAG, "Credential is not of type Google ID!")
          }
      }
      private void handleSignIn(Credential credential) {
          // Check if credential is of type Google ID
          if (credential instanceof CustomCredential customCredential
                  && credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)) {
              // Create Google ID Token
              Bundle credentialData = customCredential.getData();
              GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credentialData);
      
              // Sign in to Firebase with using the token
              firebaseAuthWithGoogle(googleIdTokenCredential.getIdToken());
          } else {
              Log.w(TAG, "Credential is not of type Google ID!");
          }
      }
  2. ログイン アクティビティの onCreate メソッドで、FirebaseAuth オブジェクトの共有インスタンスを取得します。
    KotlinJava
    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth
    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. アクティビティを初期化するときに、ユーザーが現在ログインしているかどうかを確認します。
    KotlinJava
    override fun onStart() {
        super.onStart()
        // Check if user is signed in (non-null) and update UI accordingly.
        val currentUser = auth.currentUser
        updateUI(currentUser)
    }
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
  4. 手順 1 で作成したユーザーの Google ID トークンを取得して Firebase 認証情報と交換し、Firebase 認証情報を使用して Firebase に対して認証を行います。
    KotlinJava
    private fun firebaseAuthWithGoogle(idToken: String) {
        val credential = GoogleAuthProvider.getCredential(idToken, null)
        auth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithCredential:success")
                    val user = auth.currentUser
                    updateUI(user)
                } else {
                    // If sign in fails, display a message to the user
                    Log.w(TAG, "signInWithCredential:failure", task.exception)
                    updateUI(null)
                }
            }
    }
    private void firebaseAuthWithGoogle(String idToken) {
        AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        updateUI(null);
                    }
                });
    }
    signInWithCredential の呼び出しが成功した場合は、getCurrentUser メソッドを使用してユーザーのアカウント データを取得できます。

次のステップ

ユーザーが初めてログインすると、新しいユーザー アカウントが作成され、ユーザーがログイン時に使用した認証情報(ユーザー名とパスワード、電話番号、または認証プロバイダ情報)にアカウントがリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのログイン方法にかかわらず、プロジェクトのすべてのアプリでユーザーを識別するために使用できます。

  • アプリでは、FirebaseUser オブジェクトからユーザーの基本的なプロフィール情報を取得できます。ユーザーを管理するをご覧ください。

  • Firebase Realtime DatabaseCloud Storageセキュリティ ルールでは、ログイン済みユーザーの一意のユーザー ID を auth 変数から取得し、それを使用して、ユーザーがアクセスできるデータを制御できます。

既存のユーザー アカウントに認証プロバイダの認証情報をリンクすることで、ユーザーは複数の認証プロバイダを使用してアプリにログインできるようになります。

ユーザーのログアウトを行うには、signOut を呼び出します。 また、認証情報マネージャーのドキュメントで推奨されているように、すべての認証情報プロバイダから現在のユーザー認証情報の状態を消去する必要があります。

KotlinJava
private fun signOut() {
    // Firebase sign out
    auth.signOut()

    // When a user signs out, clear the current user credential state from all credential providers.
    lifecycleScope.launch {
        try {
            val clearRequest = ClearCredentialStateRequest()
            credentialManager.clearCredentialState(clearRequest)
            updateUI(null)
        } catch (e: ClearCredentialException) {
            Log.e(TAG, "Couldn't clear user credentials: ${e.localizedMessage}")
        }
    }
}
private void signOut() {
    // Firebase sign out
    mAuth.signOut();

    // When a user signs out, clear the current user credential state from all credential providers.
    ClearCredentialStateRequest clearRequest = new ClearCredentialStateRequest();
    credentialManager.clearCredentialStateAsync(
            clearRequest,
            new CancellationSignal(),
            Executors.newSingleThreadExecutor(),
            new CredentialManagerCallback<>() {
                @Override
                public void onResult(@NonNull Void result) {
                    updateUI(null);
                }

                @Override
                public void onError(@NonNull ClearCredentialException e) {
                    Log.e(TAG, "Couldn't clear user credentials: " + e.getLocalizedMessage());
                }
            });
}