將應用程式連結至 Firebase
如果您尚未將 Firebase 新增至 Android 專案,請先新增。
在應用程式中新增 Firebase Authentication
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,加入 Android 適用的 Firebase Authentication 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.0.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:24.0.0") }
如要使用驗證供應商,請在 Firebase 控制台中啟用。前往「Sign-in Method」頁面,在 Firebase Authentication 區段中啟用電子郵件/密碼登入功能,以及您要為應用程式使用的任何其他身分識別供應商。
(選用) 使用 Firebase Local Emulator Suite 製作原型並進行測試
在說明應用程式如何驗證使用者之前,我們先介紹一組可用於原型設計和測試 Authentication 功能的工具:Firebase Local Emulator Suite。如果您正在決定要使用哪種驗證技術和供應商、嘗試使用 Authentication 和 Firebase Security Rules 搭配公開和私人資料的不同資料模型,或是製作登入 UI 設計的原型,那麼在不部署即時服務的情況下,於本機作業會是個好主意。
Authentication模擬器是 Local Emulator Suite 的一部分,可讓應用程式與模擬的資料庫內容和設定互動,以及選擇性地與模擬的專案資源 (函式、其他資料庫和安全性規則) 互動。
使用 Authentication 模擬器只需幾個步驟:
- 在應用程式的測試設定中加入一行程式碼,即可連線至模擬器。
- 從本機專案目錄的根目錄執行
firebase emulators:start
。 - 使用 Local Emulator Suite UI 進行互動式原型設計,或使用 Authentication 模擬器 REST API 進行非互動式測試。
如需詳細指南,請參閱「將應用程式連線至 Authentication 模擬器」。詳情請參閱Local Emulator Suite簡介。
接下來,我們將繼續說明如何驗證使用者。
檢查目前的驗證狀態
宣告
FirebaseAuth
的例項。Kotlin
private lateinit var auth: FirebaseAuth
Java
private FirebaseAuth mAuth;
在
onCreate()
方法中,初始化FirebaseAuth
例項。Kotlin
// Initialize Firebase Auth auth = Firebase.auth
Java
// Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
初始化 Activity 時,請檢查使用者目前是否已登入。
Kotlin
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
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
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
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(); }
後續步驟
如要瞭解如何新增其他身分和驗證服務,請參閱下列指南: