![](/img/trans.png)
[英]How to link Phone with Email and Password Authentication in Firebase?
[英]Firebase email/password authentication - how to require email verification?
每當我在 Firebase 中使用電子郵件/密碼身份驗證提供程序時,即使emailVerified
為false
,提供程序也會在成功注冊后發送不記名令牌。 有沒有一種開箱即用的方法可以將電子郵件/密碼身份驗證提供程序配置為在用戶驗證其 email 地址之前不發送不記名令牌(並返回 403 錯誤)?
請注意,我知道如何創建用戶、登錄用戶、發送驗證 email 等...使用 firebase v9.x 通過方法createUserWithEmailAndPassword
、 signInWithEmailAndPassword
、 signOut
、 sendEmailVerification
來自 firebase firebase/auth
。 我只是問是否有一種方法可以設置提供者的行為,而不必為此編寫我自己的處理程序 function。 我希望它在需要 email 驗證時表現得像 Cognito 一樣。
沒有辦法要求驗證用戶的 email 地址,然后才能登錄 Firebase 身份驗證。
您可以獲得的最接近的方法是使用電子郵件鏈接登錄,它將登錄和驗證用戶的 email 地址結合在一個操作中。
但這是您通常希望在應用程序代碼中實現它的方式:
與數據訪問相同:如果您有自定義后端代碼,您可以檢查 email 地址是否也在 ID 令牌以及 Firebase 的服務器端安全規則中得到驗證。
根據文檔,您可以使用阻止功能來要求 email 驗證注冊(只是它不起作用):
exports.beforeCreate = functions.auth.user().beforeCreate((user, context) => {
const locale = context.locale;
if (user.email && !user.emailVerified) {
// Send custom email verification on sign-up.
return admin.auth().generateEmailVerificationLink(user.email).then((link) => {
return sendCustomVerificationEmail(user.email, link, locale);
});
}
});
exports.beforeSignIn = functions.auth.user().beforeSignIn((user, context) => {
if (user.email && !user.emailVerified) {
throw new functions.auth.HttpsError(
'invalid-argument', `"${user.email}" needs to be verified before access is granted.`);
}
});
generateEmailVerificationLink
始終返回以下錯誤:
"err": {
"message": "There is no user record corresponding to the provided identifier.",
"code": "auth/user-not-found"
},
但無論如何都會創建用戶,因為beforeCreate
不會返回異常。
如果您想自己檢查,只需記錄錯誤:
return admin.auth().generateEmailVerificationLink(user.email)
.then((link) => {
functions.logger.info("link", {user: user, context: context, link: link})
})
.catch((err) => {
functions.logger.info("error", {user: user, context: context, err: err});
});
createUserWithEmailAndPassword()
將在創建帳戶后立即登錄用戶。 此外,即使他們的 email 未經過驗證,也沒有任何方法可以阻止用戶登錄,但您實際上可以檢查 email 是否在安全規則中經過驗證,或者使用 Admin SDK 來阻止未經驗證的 email 用戶訪問您的資源。 您可以在 Firestore 中使用此規則:
allow read, write: if request.auth.token.email_verified == true;
一種解決方法是使用Cloud function和Admin SDK創建用戶,這不會讓用戶登錄,但請注意用戶可以登錄。
如果你想阻止登錄,除非 email 被嚴格驗證,那么你可以在創建帳戶后立即禁用它。 現在您可能無法使用要求用戶首先登錄的sendEmailVerification()
,您始終可以創建自己的解決方案來驗證 email。該過程可能類似於:
此外,用戶仍然可以使用 REST API 創建帳戶,但您可以禁用注冊,以便只能通過 Cloud function 創建用戶,這會立即禁用用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.