將您的應用程式連接到 Firebase
如果您尚未將 Firebase 新增至您的 Android 專案中,請將其新增至您的 Android 專案中。
將 Firebase 身份驗證新增至您的應用
在模組(應用程式層級)Gradle 檔案(通常
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
)中,新增Firebase 驗證的依賴項Android 的庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.7.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") }
透過使用Firebase Android BoM ,您的應用程式將始終使用 Firebase Android 程式庫的相容版本。
正在尋找 Kotlin 特定的庫模組?從2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。(替代方法)在不使用 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:22.3.0") }
要使用身份驗證提供程序,您需要在Firebase 控制台中啟用它。前往 Firebase 驗證部分中的登入方法頁面,為您的應用程式啟用電子郵件/密碼登入和任何其他身分提供者。
(可選)使用 Firebase 本機模擬器套件進行原型設計和測試
在討論您的應用程式如何對使用者進行身份驗證之前,我們先介紹一組可用於原型設計和測試身份驗證功能的工具:Firebase Local Emulator Suite。如果您正在選擇身份驗證技術和提供者,使用身份驗證和Firebase 安全性規則嘗試使用公共和私有資料的不同資料模型,或者對登入UI 設計進行原型設計,那麼能夠在本地工作而無需部署即時服務可能是一個好主意。
身份驗證模擬器是本機模擬器套件的一部分,它使您的應用程式能夠與模擬資料庫內容和配置以及可選的模擬項目資源(函數、其他資料庫和安全規則)進行互動。
使用身份驗證模擬器只需幾個步驟:
- 將一行程式碼新增至應用程式的測試配置以連接到模擬器。
- 從本地專案目錄的根目錄中,運行
firebase emulators:start
。 - 使用本機模擬器套件 UI 進行互動式原型設計,或使用驗證模擬器 REST API 進行非互動式測試。
詳細指南可在將您的應用程式連接到身份驗證模擬器中找到。有關詳細信息,請參閱本地模擬器套件簡介。
現在讓我們繼續了解如何對使用者進行身份驗證。
檢查目前的身份驗證狀態
聲明
FirebaseAuth
的實例。Kotlin+KTX
private lateinit var auth: FirebaseAuth
Java
private FirebaseAuth mAuth;
在
onCreate()
方法中,初始化FirebaseAuth
實例。Kotlin+KTX
// Initialize Firebase Auth auth = Firebase.auth
Java
// Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
初始化您的活動時,檢查使用者目前是否已登入。
Kotlin+KTX
public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser if (currentUser != null) { reload() } }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
註冊新用戶
建立一個新的createAccount
方法,該方法接受電子郵件地址和密碼,對其進行驗證,然後使用createUserWithEmailAndPassword
方法建立一個新使用者。
Kotlin+KTX
auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } }
Java
mAuth.createUserWithEmailAndPassword(email, password) .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, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
新增表單以使用電子郵件和密碼註冊新用戶,並在提交時呼叫此新方法。您可以在我們的快速入門範例中查看範例。
登入現有用戶
建立一個新的signIn
方法,該方法接受電子郵件地址和密碼,對其進行驗證,然後使用signInWithEmailAndPassword
方法讓使用者登入。
Kotlin+KTX
auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT, ).show() updateUI(null) } }
Java
mAuth.signInWithEmailAndPassword(email, password) .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, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
新增一個表單以使用電子郵件和密碼登入用戶,並在提交時呼叫此新方法。您可以在我們的快速入門範例中查看範例。
存取用戶資訊
如果使用者已成功登錄,您可以隨時使用getCurrentUser
方法來取得他們的帳戶資料。
Kotlin+KTX
val user = Firebase.auth.currentUser user?.let { // Name, email address, and profile photo Url val name = it.displayName val email = it.email val photoUrl = it.photoUrl // Check if user's email is verified val emailVerified = it.isEmailVerified // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. val uid = it.uid }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // Check if user's email is verified boolean emailVerified = user.isEmailVerified(); // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. String uid = user.getUid(); }
下一步
瀏覽新增其他身分和身分驗證服務的指南: