將您的應用連接到 Firebase
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
將 Firebase 身份驗證添加到您的應用
在您的模塊(應用級)Gradle 文件(通常為<project>/<app-module>/build.gradle
)中,添加 Firebase 身份驗證 Android 庫的依賴項。我們建議使用Firebase Android BoM來控制庫版本。 Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.1.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' }
通過使用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:22.0.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.1.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 庫。
(備選)在不使用 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.0.0' }
要使用身份驗證提供程序,您需要在Firebase 控制台中啟用它。轉到 Firebase 身份驗證部分中的登錄方法頁面,為您的應用啟用電子郵件/密碼登錄和任何其他身份提供商。
(可選)使用 Firebase Local Emulator Suite 製作原型並進行測試
在討論您的應用程序如何對用戶進行身份驗證之前,讓我們先介紹一組可用於製作原型和測試身份驗證功能的工具:Firebase Local Emulator Suite。如果您要在身份驗證技術和提供者之間做出決定,使用身份驗證和 Firebase 安全規則嘗試使用公共和私有數據的不同數據模型,或者對登錄 UI 設計進行原型設計,那麼能夠在不部署實時服務的情況下在本地工作可能是個好主意.
身份驗證模擬器是本地模擬器套件的一部分,它使您的應用程序能夠與模擬的數據庫內容和配置以及可選的模擬項目資源(函數、其他數據庫和安全規則)進行交互。
使用 Authentication 模擬器只需要幾個步驟:
- 在您的應用程序的測試配置中添加一行代碼以連接到模擬器。
- 從本地項目目錄的根目錄運行
firebase emulators:start
。 - 使用本地模擬器套件 UI 進行交互式原型設計,或使用身份驗證模擬器 REST API 進行非交互式測試。
詳細指南可在將您的應用程序連接到身份驗證模擬器中找到。有關詳細信息,請參閱Local Emulator Suite 介紹。
現在讓我們繼續介紹如何對用戶進行身份驗證。
檢查當前授權狀態
聲明
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();
初始化 Activity 時,檢查用戶當前是否已登錄。
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(); }
下一步
瀏覽有關添加其他身份和身份驗證服務的指南: