使用Firebase重新验证

1mrurvl1  于 2023-02-09  发布在  其他
关注(0)|答案(8)|浏览(148)

我希望你能帮助我如何在Firebase中重新验证一个用户。我想知道如果文档没有解释如何使用它,那么添加所有这些伟大的特性是否有意义:
目前,这是我正在尝试的,它不工作。错误为cannot read property 'credential' of undefined
在构造函数中:

constructor(@Inject(FirebaseApp) firebaseApp: any) {
    this.auth = firebaseApp.auth();
    console.log(this.auth);
  }

那么函数

changePassword(passwordData) {
    if(passwordData.valid) {
      console.log(passwordData.value);
      // let us reauthenticate first irrespective of how long
      // user's been logged in!

      const user = this.auth.currentUser;
      const credential = this.auth.EmailAuthProvider.credential(user.email, passwordData.value.oldpassword);
      console.log(credential);
      this.auth.reauthenticate(credential)
        .then((_) => {
          console.log('User reauthenticated');
          this.auth.updatePassword(passwordData.value.newpassword)
            .then((_) => {
              console.log('Password changed');
            })
            .catch((error) => {
              console.log(error);
            })
        })
        .catch((error) => {
          console.log(error);
        })
    }
  }
6ioyuze2

6ioyuze21#

reauthenticate()方法在firebase.User上调用,而不是在firebase.auth.Auth本身上调用。

var user = firebase.app.auth().currentUser;
var credentials = firebase.auth.EmailAuthProvider.credential('puf@firebaseui.com', 'firebase');
user.reauthenticate(credentials);

更新(2017年7月)

Firebase Web SDK 4.0版本中有一些突破性的更改。从发行说明中可以看到:
中断:已删除firebase.User.prototype.reauthenticate,以支持firebase.User.prototype.reauthenticateWithCredential
据我所知,reauthenticateWithCredential是旧方法的替代品。

mpbci0fu

mpbci0fu2#

这里有一些代码,可以让用户(a)在Firebase中重新验证,以及(b)在为我重新验证后更改他们的密码。在写这篇文章时,我研究了大约一个小时,所以希望它能节省一些时间。
在VueJS中写道:

changePassword() {
            let self = this; // i use "self" to get around scope issues
            var user = firebase.auth().currentUser;
            var credential = firebase.auth.EmailAuthProvider.credential(
                this.$store.state.userId, // references the user's email address
                this.oldPassword
            );

            user.reauthenticateWithCredential(credential)
                .then(function() {
                    // User re-authenticated.
                    user.updatePassword(self.newPassword) 
                        .then(function() {
                            console.log("Password update successful!");
                        })
                        .catch(function(error) {
                            console.log(
                                "An error occurred while changing the password:",
                                error
                            );
                        });
                })
                .catch(function(error) {
                    console.log("Some kinda bug: ", error);
                    // An error happened.
                });
b09cbbtk

b09cbbtk3#

截至2019年5月略有变化,更多详情见此处,代码如下:

var user = firebase.auth().currentUser;
var credential = firebase.auth.EmailAuthProvider.credential(user.email, password);

// Prompt the user to re-provide their sign-in credentials
return user.reauthenticateWithCredential(credential);
qrjkbowd

qrjkbowd4#

onPressed中直接调用changeEmail("new email","password")以更新用户电子邮件,不需要重新验证错误

RaisedButton(
  onPressed: () {
    changeEmail(_emailController.text, _passwordController.text);
  }              

 Future<void> changeEmail(String email, String password) async {
   User user = await FirebaseAuth.instance.currentUser;
  print(email);
  print(password);
  try {
    try {
      var authResult = await user.reauthenticateWithCredential(
        EmailAuthProvider.getCredential(
          email: user.email,
          password: password,
        ),
      );
      user.updateEmail(email).then((_) {
        print("Succesfull changed email");
        _backthrow();
      }).catchError((error) {
        showAlertDialog(context, error.message);
        print("email can't be changed" + error.toString());
      });
      return null;
    } catch (e) {
      print("2");
    }
  } catch (e) {
    print(e.message);
    showAlertDialog(context, e.message);
  }
}
c0vxltue

c0vxltue5#

她是一个完整的例子,如何重新认证与Firebase

var pass = "abcdefg";
var user = firebase.auth().currentUser;
var credential = firebase.auth.EmailAuthProvider.credential(user.email, pass);

user.reauthenticateWithCredential(credential).then(() => {
    console.log("Its good!");
}).catch((error) => {
    console.log(error);
});
fkaflof6

fkaflof66#

**自2021年以来:**如果您使用Firebase JS API 9.x(树可摇动版本),这是最新的方式:

https://cloud.google.com/identity-platform/docs/web/reauth

带着证书

import { getAuth, reauthenticateWithCredential } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

// todo for you: prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();

reauthenticateWithCredential(user, credential).then(() => {
  // ...
}).catch((error) => {
  // ...
});

带弹出窗口

import { getAuth, reauthenticateWithPopup, OAuthProvider } from "firebase/auth";

const auth = getAuth();
// todo for you: change to appropriate provider
const provider = new OAuthProvider('apple.com');

reauthenticateWithPopup(auth.currentUser, provider)
  .then((result) => {
    // ...
  })
  .catch((error) => {
    // ...
  });
zbsbpyhn

zbsbpyhn7#

以下是我在Firebase中重新验证用户的方法:

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

const auth = getAuth()

const reauthenticateUser = async (email, password) => {
  const user = auth.currentUser;
  try {
    const credential = EmailAuthProvider.credential(email, password);
    await reauthenticateWithCredential(user, credential)
  } catch (error) {
    Alert.alert("Error", "The email or password is incorrect. Please try again.")
  }
}
yiytaume

yiytaume8#

我在保存主电子邮件时收到重新验证错误auth/requires-recent-login
我不知道如何实现这个文档不全的reauthenticateWithCredential(credential)方法,所以,我简单地注销了用户并重定向到登录页面。这是一个黑客,但它的工作方式很有魅力!

firebase.auth().signOut();

相关问题