您可以使用 Firebase 驗證讓您的使用者使用電子郵件地址和密碼透過 Firebase 進行身份驗證。
在你開始之前
如果您還沒有這樣做,請按照入門指南中的步驟操作。
啟用電子郵件/密碼登入:
- 在 Firebase 控制台的驗證部分中,開啟登入方法頁面。
- 在「登入方法」頁面中,啟用電子郵件/密碼登入方法,然後按一下「儲存」 。
建立基於密碼的帳戶
若要建立帶有密碼的新使用者帳戶,請呼叫createUserWithEmailAndPassword()
方法:
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailAddress,
password: password,
);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
通常,您可以從應用程式的註冊畫面執行此操作。當新使用者使用應用程式的註冊表單進行註冊時,請完成應用程式要求的所有新帳戶驗證步驟,例如驗證新帳戶的密碼是否正確輸入並滿足您的複雜性要求。
如果新帳戶建立成功,則使用者也已登入。如果您正在偵聽身份驗證狀態的更改,則會向您的偵聽器發送新事件。
作為建立新帳戶的後續操作,您可以驗證使用者的電子郵件地址。
使用電子郵件地址和密碼登入用戶
使用密碼登入使用者的步驟與建立新帳戶的步驟類似。從應用程式的登入畫面中,呼叫signInWithEmailAndPassword()
:
try {
final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: emailAddress,
password: password
);
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
下一步
用戶建立新帳戶後,該帳戶將作為 Firebase 專案的一部分存儲,並且可用於在專案中的每個應用程式中識別用戶,無論用戶使用哪種登入方法。
在您的應用程式中,您可以從User
物件取得使用者的基本個人資料資訊。請參閱管理用戶。
在 Firebase 即時資料庫和雲端儲存安全性規則中,您可以從auth
變數取得登入使用者的唯一使用者 ID,並使用它來控制使用者可以存取哪些資料。
您可以透過將身分驗證提供者憑證連結到現有使用者帳戶,允許使用者使用多個驗證提供者登入您的應用程式。
若要登出用戶,請呼叫signOut()
:
await FirebaseAuth.instance.signOut();