Google ログインをアプリに統合して、ユーザーが Firebase での認証に Google アカウントを使用できるようにすることができます。
はじめに
まだ追加していない場合は、Firebase を Android プロジェクトに追加します。
Firebase Android BoM を使用して、モジュール(アプリレベル)の Gradle ファイル(通常は
app/build.gradle
)で Firebase Authentication Android ライブラリの依存関係を宣言します。また、Firebase Authentication の設定の一環として、Google Play 開発者サービス SDK をアプリに追加する必要もあります。
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.2.0') // Declare 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 declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }Firebase Android BoM を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。
(別の方法)BoM を使用せずに Firebase ライブラリの依存関係を宣言する
Firebase BoM を使用しない場合は、依存関係の行でそれぞれの Firebase ライブラリのバージョンを指定する必要があります。
アプリで複数の Firebase ライブラリを使用する場合は、すべてのバージョンの互換性を確保するため、ライブラリのバージョンの管理に BoM を使用することを強くおすすめします。
dependencies { // Declare 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:20.0.1'
// Also declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.2.0') // Declare 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 declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }Firebase Android BoM を使用すると、アプリは常に互換性のあるバージョンの Firebase Android ライブラリを使用します。
(別の方法)BoM を使用せずに Firebase ライブラリの依存関係を宣言する
Firebase BoM を使用しない場合は、依存関係の行でそれぞれの Firebase ライブラリのバージョンを指定する必要があります。
アプリで複数の Firebase ライブラリを使用する場合は、すべてのバージョンの互換性を確保するため、ライブラリのバージョンの管理に BoM を使用することを強くおすすめします。
dependencies { // Declare 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:20.0.1'
// Also declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }アプリの SHA-1 フィンガープリントを指定していない場合は、Firebase コンソールの [設定] ページで指定します。アプリの SHA-1 フィンガープリントを取得する方法の詳細については、クライアントの認証をご覧ください。
- Firebase コンソールで Google ログインを有効にします。
- Firebase コンソールで [Authentication] セクションを開きます。
- [ログイン方法] タブで [Google] を有効にし、[保存] をクリックします。
Firebase で認証する
- Android アプリへの Google ログインの統合ページの手順に沿って Google ログインをアプリに統合します。
GoogleSignInOptions
オブジェクトを構成するときは、requestIdToken
を呼び出します。Java
// Configure Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build();
Kotlin+KTX
// Configure Google Sign In val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build()
requestIdToken
メソッドに渡す必要があります。OAuth 2.0 クライアント ID を確認するには:- GCP Console で [認証情報] ページに移動します。
- ウェブ アプリケーション タイプのクライアント ID がバックエンド サーバーの OAuth 2.0 クライアント ID です。
Java
private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId()); firebaseAuthWithGoogle(account.getIdToken()); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); // ... } } }
Kotlin+KTX
private fun signIn() { val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { // Google Sign In was successful, authenticate with Firebase val account = task.getResult(ApiException::class.java)!! Log.d(TAG, "firebaseAuthWithGoogle:" + account.id) firebaseAuthWithGoogle(account.idToken!!) } catch (e: ApiException) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e) // ... } } }
- ログイン アクティビティの
onCreate
メソッドで、FirebaseAuth
オブジェクトの共有インスタンスを取得します。Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- アクティビティを初期化するときに、ユーザーが現在ログインしているかどうかを確認します。
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); }
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) }
- ユーザーがログインに成功したら、
GoogleSignInAccount
オブジェクトから ID トークンを取得して Firebase 認証情報と交換し、Firebase 認証情報を使用して Firebase での認証を行います。Java
private void firebaseAuthWithGoogle(String idToken) { AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(credential) .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()); Snackbar.make(mBinding.mainLayout, "Authentication Failed.", Snackbar.LENGTH_SHORT).show(); updateUI(null); } // ... } }); }
Kotlin+KTX
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) // ... Snackbar.make(view, "Authentication Failed.", Snackbar.LENGTH_SHORT).show() updateUI(null) } // ... } }
signInWithCredential
の呼び出しが成功した場合は、getCurrentUser
メソッドを使用してユーザーのアカウント データを取得できます。
次のステップ
ユーザーが初めてログインすると、新しいユーザー アカウントが作成され、ユーザーがログインに使用した認証情報(ユーザー名とパスワード、電話番号、または認証プロバイダ情報)にアカウントがリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのログイン方法にかかわらず、プロジェクトのすべてのアプリでユーザーを識別するために使用できます。
-
アプリでは、
FirebaseUser
オブジェクトからユーザーの基本的なプロフィール情報を取得します。ユーザーを管理するをご覧ください。 Firebase Realtime Database と Cloud Storage のセキュリティ ルールでは、ログイン済みユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用して、ユーザーがアクセスできるデータを管理できます。
既存のユーザー アカウントに認証プロバイダの認証情報をリンクすることで、ユーザーは複数の認証プロバイダを使用してアプリにログインできるようになります。
ユーザーのログアウトを行うには、signOut
を呼び出します。
Java
FirebaseAuth.getInstance().signOut();
Kotlin+KTX
Firebase.auth.signOut()