Google致力於提高黑人社區的種族平等。 怎麼看。
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

在Android上使用Google登錄進行身份驗證

通過將Google登錄功能集成到您的應用中,您可以讓用戶使用其Google帳戶向Firebase進行身份驗證。

在你開始之前

  1. 如果尚未將Firebase添加到您的Android項目中
  2. 在項目級別的build.gradle文件中,確保在buildscriptallprojects部分中都包含Google的Maven存儲庫。
  3. 將Firebase身份驗證Android庫和Google Play服務的依賴項添加到模塊(應用程序級)Gradle文件(通常為app/build.gradle )中:

     implementation 'com.google.firebase:firebase-auth:19.3.2'
    implementation 'com.google.android.gms:play-services-auth:18.1.0'
     
  4. 如果您尚未指定應用的SHA-1指紋,請從Firebase控制台的“設置”頁面進行。有關如何獲取應用程序的SHA-1指紋的詳細信息,請參閱身份驗證客戶端

  5. 在Firebase控制台中啟用Google登錄:
    1. Firebase控制台中 ,打開“ 身份驗證”部分。
    2. 登錄方法標籤上,啟用Google登錄方法,然後點擊保存

使用Firebase進行身份驗證

  1. 遵循將Google登錄功能集成到您的Android應用頁面中的步驟, 將Google登錄功能集成到您的應用中 。配置GoogleSignInOptions對象時,請調用requestIdToken

    爪哇

    // 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()
    您必須將服務器的客戶端ID傳遞給requestIdToken方法。要查找OAuth 2.0客戶端ID,請執行以下操作:
    1. 在GCP控制台中打開“ 憑據”頁面
    2. Web應用程序類型客戶端ID是您的後端服務器的OAuth 2.0客戶端ID。
    集成Google登錄後,您的登錄活動將具有類似於以下內容的代碼:

    爪哇

    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)
                // ...
            }
        }
    }
  2. 在登錄活動的onCreate方法中,獲取FirebaseAuth對象的共享實例:

    爪哇

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    Kotlin + KTX

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth
  3. 初始化活動時,請檢查用戶當前是否登錄:

    爪哇

    @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)
    }
  4. 用戶成功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());
                            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實時數據庫和雲存儲安全規則中 ,您可以從auth變量中獲取登錄用戶的唯一用戶ID,然後使用它來控制用戶可以訪問哪些數據。

通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,可以允許用戶使用多個身份驗證提供程序登錄您的應用程序

要註銷用戶,請致電signOut

爪哇

FirebaseAuth.getInstance().signOut();

Kotlin + KTX

Firebase.auth.signOut()