ユーザーが Google アカウントを使用して Firebase で認証できるようにすることができます。
あなたが始める前に
まだ行っていない場合は、 Firebase を Android プロジェクトに追加します。
モジュール (アプリ レベル) の Gradle ファイル(通常は
<project>/<app-module>/build.gradle
) で、Firebase Authentication Android ライブラリの依存関係を追加します。ライブラリのバージョン管理には、 Firebase Android BoMを使用することをお勧めします。また、Firebase Authentication の設定の一環として、Google Play サービス SDK をアプリに追加する必要があります。
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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-ktx'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }Firebase Android BoMを使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。
(代替) BoM を使用せずに Firebase ライブラリの依存関係を追加する
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-ktx:21.1.0'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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 dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }Firebase Android BoMを使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。
(代替) BoM を使用せずに Firebase ライブラリの依存関係を追加する
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:21.1.0'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }アプリの SHA-1 フィンガープリントをまだ指定していない場合は、Firebase コンソールの[設定] ページから指定してください。アプリの SHA-1 フィンガープリントを取得する方法の詳細については、クライアントの認証を参照してください。
- Firebase コンソールでサインイン方法として Google を有効にします。
- Firebase コンソールで、 Authセクションを開きます。
- [サインイン方法] タブで、 Googleサインイン方法を有効にし、[保存] をクリックします。
Firebase で認証する
- 保存した資格情報でユーザーをサインインするページの手順に従って、Google One Tap サインインをアプリに統合します。
BeginSignInRequest
オブジェクトを構成するときは、setGoogleIdTokenRequestOptions
を呼び出します。「サーバー」クライアント ID をKotlin+KTX
signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions( BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) // Your server's client ID, not your Android client ID. .setServerClientId(getString(R.string.your_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build()) .build()
Java
signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions(GoogleIdTokenRequestOptions.builder() .setSupported(true) // 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()) .build();
setGoogleIdTokenRequestOptions
メソッドに渡す必要があります。 OAuth 2.0 クライアント ID を見つけるには:- GCP Console で [ Credentials] ページを開きます。
- Web アプリケーションタイプのクライアント ID は、バックエンド サーバーの OAuth 2.0 クライアント ID です。
Kotlin+KTX
class YourActivity : AppCompatActivity() { // ... private val REQ_ONE_TAP = 2 // Can be any integer unique to the Activity private var showOneTapUI = true // ... override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQ_ONE_TAP -> { try { val credential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = credential.googleIdToken when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with Firebase. Log.d(TAG, "Got ID token.") } else -> { // Shouldn't happen. Log.d(TAG, "No ID token!") } } } catch (e: ApiException) { // ... } } } // ... }
Java
public class YourActivity extends AppCompatActivity { // ... private static final int REQ_ONE_TAP = 2; // Can be any integer unique to the Activity. private boolean showOneTapUI = true; // ... @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_ONE_TAP: try { SignInCredential credential = oneTapClient.getSignInCredentialFromIntent(data); String idToken = credential.getGoogleIdToken(); if (idToken != null) { // Got an ID token from Google. Use it to authenticate // with Firebase. Log.d(TAG, "Got ID token."); } } catch (ApiException e) { // ... } break; } } }
- サインイン アクティビティの
onCreate
メソッドで、FirebaseAuth
オブジェクトの共有インスタンスを取得します。Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- アクティビティを初期化するときに、ユーザーが現在サインインしているかどうかを確認します。
Kotlin+KTX
override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); }
-
onActivityResult()
ハンドラー (ステップ 1 を参照) で、ユーザーの Google ID トークンを取得し、それを Firebase 資格情報と交換し、Firebase 資格情報を使用して Firebase で認証します。Kotlin+KTX
val googleCredential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = googleCredential.googleIdToken when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with Firebase. val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(firebaseCredential) .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) } } } else -> { // Shouldn't happen. Log.d(TAG, "No ID token!") } }
Java
SignInCredential googleCredential = oneTapClient.getSignInCredentialFromIntent(data); String idToken = googleCredential.getGoogleIdToken(); if (idToken != null) { // Got an ID token from Google. Use it to authenticate // with Firebase. AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(firebaseCredential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> 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 Database と Cloud Storageセキュリティ ルールでは、サインインしているユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用してユーザーがアクセスできるデータを制御できます。
認証プロバイダーの資格情報を既存のユーザー アカウントにリンクすることで、ユーザーが複数の認証プロバイダーを使用してアプリにサインインできるようにすることができます。
ユーザーをサインアウトするには、 signOut
を呼び出します。
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();