javascript - 无法使用 Firebase 中的电子邮件链接重新进行身份验证

标签 javascript firebase firebase-authentication

我在我的网络应用程序中设置了电子邮件链接登录,它工作正常。但是,我需要在执行某个操作之前重新验证用户身份。

我正在使用以下代码重新进行身份验证:

let credential = firebase.auth.EmailAuthProvider.credentialWithLink(userEmail, window.location.href);

firebase.auth().currentUser.reauthenticateWithCredential(credential).then(function (usercred: any) {
     console.log('Reauthentication test successful.');
}).catch(function (error: any) {
     console.log('Reauthentication test failed.');
});

但是,凭证每次都会引发错误:
code: "auth/argument-error"
message: "Invalid email link!"

即使我尝试更改 URL 也是如此。该 url 在控制台中获得授权,并且是 https (我最初在 localhost 上进行测试,并认为这可能是问题所在)。

有任何想法吗?

最佳答案

我遇到了同样的问题,documentation在这个过程中有点模糊。我不想使用已经存在的 UI 解决方案(😅),所以我必须弄清楚。
这是文档片段:

import { getAuth, linkWithCredential, EmailAuthProvider } from "firebase/auth";

// Construct the email link credential from the current URL.
const credential = EmailAuthProvider.credentialWithLink(
  email, window.location.href);

// Link the credential to the current user.
const auth = getAuth();
linkWithCredential(auth.currentUser, credential)
  .then((usercred) => {
    // The provider is now successfully linked.
    // The phone user can now sign in with their phone number or email.
  })
  .catch((error) => {
    // Some error occurred.
  });

代码 window.location.href假设您正在打开来自电子邮件链接登录的链接
  • Server side / Function
  • 或发送from the client
  • 也是一个很好的阅读好流量Passing State in Email Actions

  • 它与其他电子邮件链接过程没有太大区别,您必须触发从客户端或服务器发送的电子邮件。
    我会得到 handle the other modes 的页面(密码重置,...)以及处理新身份验证或仅在页面加载时重新身份验证的特定逻辑。
    这是基于 documentation 的 Angular (Typescript) 示例
    // app.component.ts
    
    ngAfterViewInit() {
      const currentUrl = window.location.href;
      if (isSignInWithEmailLink(this.authService.auth, currentUrl)) {
        const isLoggedIn = !!this.user?.uid;
        let email = isLoggedIn
          ? this.user?.email
          : window.localStorage.getItem("emailForSignIn");
        if (!email) {
          email = window.prompt("Please provide your email for confirmation");
        }
        if (email && validateEmail(email)) {
          try {
            // --> important !
    
            if (isLoggedIn) {
               const credential = EmailAuthProvider.credentialWithLink(email,currentUrl);
                await reauthenticateWithCredential(this.user, credential)
            } else {
                 await signInWithEmailLink(
                this.authService.auth,
                email,
                currentUrl
              );
            }
            window.localStorage.removeItem("emailForSignIn");
            this.router.navigateByUrl("/login");
            // console.log(userCredential);
          } catch (e) {
            console.log(e);
            // Some error occurred, you can inspect the code: error.code
            // Common errors could be invalid email and invalid or expired OTPs.
            this.toastr.error(getTranslation(e.code), "Error");
          }
        } else {
          this.toastr.error("Please enter a valid email", "Error");
        }
      }
    }
    

    关于javascript - 无法使用 Firebase 中的电子邮件链接重新进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57664786/

    相关文章:

    firebase - 如何从http ://localhost:3000访问Firebase

    javascript - 单元测试数组推送

    android - com.google.firebase.firestore.FirebaseFirestoreException : Failed to get document because the client is offline. Android

    android - 按优先级(从最低到最高)检索 Firebase 数据不起作用?

    firebase - 存储和转换 MaterialColors

    amazon-web-services - AWS AppSync with Firebase 作为 OpenID Connect 提供商

    javascript - 为 Kendo 网格中的某些行设置 Editable False

    javascript - 在移动状态下调整 Bootstrap 轮播中的图像高度

    javascript - 重定向到 url,如果 Jwplayer 加载媒体时出错

    angularjs - 为什么我的 Angular 的 ng-show 调用仅在使用 Firebase 进行第二次点击时更新?