將應用程式連結至 Firebase
如果您尚未將 Firebase 新增至 Android 專案,請先完成這項作業。
在應用程式中加入 Firebase 驗證
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,新增 Android 專用 Firebase 驗證程式庫的依附元件。建議您使用 Firebase Android BoM 控管程式庫的版本管理。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.1.1")) // 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 程式庫版本。
(替代做法) 新增 Firebase 程式庫依附元件,「不」使用 BoM
如果選擇不使用 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:23.0.0") }
如要使用驗證供應商,您必須在 Firebase 主控台中啟用驗證供應商。前往「Firebase Authentication」區段的「Sign-in Method」頁面,啟用電子郵件/密碼登入功能,以及要為應用程式啟用的其他識別資訊提供者。
(選用) 使用 Firebase 本機模擬器套件設計原型並進行測試
在說明應用程式驗證使用者的方式之前,讓我們先介紹一組工具,可用來設計原型及測試驗證功能:Firebase 本機模擬器套件。如果您正在考慮驗證技術與供應商,建議您使用驗證和 Firebase 安全性規則,以公開和私人資料來嘗試不同的資料模型,或是設計登入 UI 的原型,而無需部署上線的服務,也能在本機運作。
驗證模擬器是本機模擬器套件的一部分,可讓應用程式與模擬資料庫內容和設定互動,並視需要選擇模擬專案資源 (函式、其他資料庫和安全性規則)。
使用驗證模擬器只需完成幾個步驟:
- 將一行程式碼新增至應用程式的測試設定,即可與模擬器連線。
- 從本機專案目錄的根目錄中執行
firebase emulators:start
。 - 使用本機模擬器套件 UI 進行互動式原型設計,或使用 Authentication Emulator 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(); }
後續步驟
探索新增其他身分識別和驗證服務的指南: