![](/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.