Firebase电子邮件链接身份验证

时间:2018-12-20 10:33:41

标签: javascript firebase firebase-authentication

我正在为项目使用无密码身份验证,一切都按预期工作,但是我对此身份验证有一个疑问。我将讨论这种情况。

第一步:众所周知,新用户需要发送电子邮件,然后点击链接进行登录。

这是正常情况,没问题,但是如果用户已经执行了该步骤并说他/她退出了应用程序,该怎么办?看来他们需要再次执行上述我的第一步。

这是我到目前为止尝试过的:

login() {
    const email = this.email;
    this.$store
      .dispatch("LOGIN", { email })
      .then(resp => {
        this.$router.replace("/");
      })
      .catch(err => {
        this.autherror = true, 
        this.errorMessage = err.message;
      });
  }

LOGIN: ({ commit }, user) => {

      return new Promise((resolve, reject) => {
        // commit(AUTH_REQUEST)
        firebase.auth().signInWithEmailLink(user.email, window.location.href)
        .then((result) => {

          window.localStorage.removeItem("emailForSignIn");
          resolve(result);
        })
        .catch((err) => {
          reject(err);
          // Some error occurred, you can inspect the code: error.code
          // Common errors could be invalid email and invalid or expired OTPs.
        });
      });
    },

尝试上面的代码时,我将收到错误消息“ 无效的电子邮件链接!”,即使我将网址作为登录时使用的上一个网址,它也会引发错误 “操作代码无效。如果代码格式错误,已过期或已被使用,则可能会发生这种情况。”

我可以理解为什么总是需要电子邮件才能登录,但是要说的重点是,如果用户首先从链接登录然后注销,则他们可以登录应用程序而无需再做第一步,如何?这意味着是否有一种将凭据存储在cookie /本地存储中的方法,并且他们唯一需要再次执行第一步的步骤是是否从所有或特定应用程序/页面中清除cookie,存储等。

那有可能吗?这肯定会改善用户体验。

1 个答案:

答案 0 :(得分:0)

您应该阅读并了解用户在Firebase中的工作方式(在任何oAuth类型验证系统中基本相同)-https://firebase.google.com/docs/auth/users

更具体地说,如何使用电子邮件-https://firebase.google.com/docs/auth/web/email-link-auth

在您的代码中,您应该使用上面参考中所示的电子邮件确认步骤(因此,类似于以下代码-您可能需要进行一些小的更改以适合您的本地情况):

LOGIN: ({ commit }, user) => {

  return new Promise((resolve, reject) => {
   // Confirm the link is a sign-in with email link.
   if (firebase.auth().isSignInWithEmailLink(window.location.href)) {
      // Additional state parameters can also be passed via URL.
      // This can be used to continue the user's intended action before triggering
      // the sign-in operation.
      // Get the email if available. This should be available if the user completes
      // the flow on the same device where they started it.
      var email = window.localStorage.getItem('emailForSignIn');
      if (!email) {
        // User opened the link on a different device. To prevent session fixation
        // attacks, ask the user to provide the associated email again. For example:
        email = window.prompt('Please provide your email for confirmation');
      }
    // commit(AUTH_REQUEST)
    firebase.auth().signInWithEmailLink(email, window.location.href)
    .then((result) => {

      window.localStorage.removeItem("emailForSignIn");
      resolve(result);
    })
    .catch((err) => {
      reject(err);
      // Some error occurred, you can inspect the code: error.code
      // Common errors could be invalid email and invalid or expired OTPs.
    });
  });
}
},
相关问题