將您的應用連接到 Firebase
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
將 Firebase 身份驗證添加到您的應用
使用Firebase Android BoM ,在模塊(應用級)Gradle 文件(通常是app/build.gradle
)中聲明 Firebase Authentication Android 庫的依賴項。 Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.1.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' }
通過使用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:21.0.6' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.1.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' }
通過使用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:21.0.6' }
要使用身份驗證提供程序,您需要在Firebase 控制台中啟用它。轉到 Firebase 身份驗證部分中的登錄方法頁面以啟用電子郵件/密碼登錄以及您希望用於您的應用的任何其他身份提供程序。
(可選)使用 Firebase 本地模擬器套件進行原型設計和測試
在討論您的應用如何對用戶進行身份驗證之前,讓我們介紹一組可用於原型化和測試身份驗證功能的工具:Firebase Local Emulator Suite。如果您要在身份驗證技術和提供者之間做出決定,使用身份驗證和 Firebase 安全規則嘗試具有公共和私有數據的不同數據模型,或者對登錄 UI 設計進行原型設計,那麼能夠在不部署實時服務的情況下在本地工作可能是一個好主意.
身份驗證模擬器是本地模擬器套件的一部分,它使您的應用程序能夠與模擬的數據庫內容和配置以及可選的模擬項目資源(函數、其他數據庫和安全規則)進行交互。
使用身份驗證模擬器只需幾個步驟:
- 在應用程序的測試配置中添加一行代碼以連接到模擬器。
- 從本地項目目錄的根目錄運行
firebase emulators:start
。 - 使用本地模擬器套件 UI 進行交互式原型設計,或使用身份驗證模擬器 REST API 進行非交互式測試。
將您的應用程序連接到身份驗證模擬器中提供了詳細指南。有關詳細信息,請參閱本地仿真器套件介紹。
現在讓我們繼續討論如何對用戶進行身份驗證。
檢查當前身份驗證狀態
聲明
FirebaseAuth
的一個實例。Java
private FirebaseAuth mAuth;
Kotlin+KTX
private lateinit var auth: FirebaseAuth
在
onCreate()
方法中,初始化FirebaseAuth
實例。Java
// Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
// Initialize Firebase Auth auth = Firebase.auth
初始化 Activity 時,檢查用戶當前是否已登錄。
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(); } }
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(); } }
註冊新用戶
創建一個新的createAccount
方法,該方法接收電子郵件地址和密碼,對其進行驗證,然後使用createUserWithEmailAndPassword
方法創建一個新用戶。
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); } } });
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) } }
添加一個表單以使用他們的電子郵件和密碼註冊新用戶,並在提交時調用此新方法。您可以在我們的快速入門示例中看到一個示例。
登錄現有用戶
創建一個新的signIn
方法,該方法接收電子郵件地址和密碼,對其進行驗證,然後使用signInWithEmailAndPassword
方法讓用戶登錄。
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); } } });
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) } }
添加一個表單以使用用戶的電子郵件和密碼登錄用戶,並在提交時調用此新方法。您可以在我們的快速入門示例中看到一個示例。
訪問用戶信息
如果用戶已成功登錄,您可以隨時使用getCurrentUser
方法獲取他們的帳戶數據。
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(); }
Kotlin+KTX
val user = Firebase.auth.currentUser user?.let { // Name, email address, and profile photo Url val name = user.displayName val email = user.email val photoUrl = user.photoUrl // Check if user's email is verified val 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.getToken() instead. val uid = user.uid }
下一步
探索有關添加其他身份和身份驗證服務的指南: