通過將Google登錄功能集成到您的應用中,您可以讓用戶使用其Google帳戶向Firebase進行身份驗證。
在你開始之前
使用Firebase Android BoM ,在模塊(應用程序級)Gradle文件(通常為
app/build.gradle
)中聲明Firebase Authentication Android庫的依賴app/build.gradle
。另外,作為設置Firebase身份驗證的一部分,您需要將Google Play服務SDK添加到您的應用中。
爪哇
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:27.0.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.4'
// 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:27.0.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.4'
// 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控制台中,打開“身份驗證”部分。
- 在登錄方法標籤上,啟用Google登錄方法,然後點擊保存。
使用Firebase進行身份驗證
- 遵循將Google登錄功能集成到您的Android應用頁面中的步驟,將Google登錄功能集成到您的應用中。在配置
GoogleSignInOptions
對象時,請調用requestIdToken
:您必須將服務器的客戶端ID傳遞給爪哇
// Configure Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Kotlin + KTX
// Configure Google Sign In val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() googleSignInClient = GoogleSignIn.getClient(this, gso)
requestIdToken
方法。要查找OAuth 2.0客戶端ID,請執行以下操作:- 在GCP控制台中打開“憑據”頁面。
- Web應用程序類型客戶端ID是您的後端服務器的OAuth 2.0客戶端ID。
爪哇
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
對象的共享實例:爪哇
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin + KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 初始化活動時,請檢查用戶當前是否登錄:
爪哇
@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
,從GoogleSignInAccount
對象獲取ID令牌,將GoogleSignInAccount
交換為Firebase憑據,然後使用Firebase憑據向Firebase進行身份驗證:如果對爪哇
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()); 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) updateUI(null) } } }
signInWithCredential
的調用成功,則可以使用getCurrentUser
方法獲取用戶的帳戶數據。
下一步
用戶首次登錄後,將創建一個新的用戶帳戶並將其鏈接到用戶登錄的憑據(即用戶名和密碼,電話號碼或身份驗證提供者信息)。這個新帳戶存儲為Firebase項目的一部分,可用於在項目中的每個應用程序中識別用戶,而無論用戶如何登錄。
在您的應用中,您可以從
FirebaseUser
對象獲取用戶的基本配置文件信息。請參閱管理用戶。在Firebase實時數據庫和雲存儲安全規則中,您可以從
auth
變量獲取登錄用戶的唯一用戶ID,並使用它來控制用戶可以訪問哪些數據。
通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,可以允許用戶使用多個身份驗證提供程序登錄您的應用程序。
要註銷用戶,請致電signOut
:
爪哇
FirebaseAuth.getInstance().signOut();
Kotlin + KTX
Firebase.auth.signOut()