如何创建 Firebase Web user.reauthenticateWithCredential() 方法所需的“凭据”对象?

2024-01-17

中的(不清楚)示例new docs https://firebase.google.com/docs/auth/web/manage-users#re-authenticate_a_user:

var user = firebase.auth().currentUser;
var credential;
// Prompt the user to re-provide their sign-in credentials
user.reauthenticateWithCredential(credential).then(function() {

我应该如何创建这个credential object?

我试过:

  • reauthenticateWithCredential(email, password)(如登录方法)
  • reauthenticateWithCredential({ email, password })(文档仅提到一个论点)

没有运气 :(

PS:我没有计算在新文档中搜索相关信息所浪费的时间...我非常想念精彩的 firebase.com 文档,但想切换到 v3 或更高版本的 firebase.storage...


我设法让它工作,对于那些不想在详尽但难以阅读的 API 参考中花费太多时间的人来说,应该更新文档以包含此内容。

Firebase 8.x

凭证对象的创​​建方式如下:

const user = firebase.auth().currentUser;
const credential = firebase.auth.EmailAuthProvider.credential(
    user.email, 
    userProvidedPassword
);
// Now you can use that to reauthenticate
user.reauthenticateWithCredential(credential);

Firebase 9.x

(感谢@Dako Junior 的回答,为了详尽起见,我将其添加到此处)

import {
    EmailAuthProvider,
    getAuth,
    reauthenticateWithCredential,
} from 'firebase/auth'

const auth = getAuth()
const credential = EmailAuthProvider.credential(
    auth.currentUser.email,
    userProvidedPassword
)
const result = await reauthenticateWithCredential(
    auth.currentUser, 
    credential
)
// User successfully reauthenticated. New ID tokens should be valid.

Note

有人问到userProvidedPassword,如果它是第一次登录时存储的某种变量。不是,您应该打开一个带有密码输入的新对话框/页面,并且用户将输入他们的密码again.

我坚持你must not尝试通过以明文形式存储用户密码来解决此问题。这是一个normal应用程序的功能。例如,在 GMail 中,有时您的会话会过期,或者怀疑遭到黑客攻击、您更改位置等。GMail 会再次要求您输入密码。这就是重新认证。

这种情况不会经常发生,但使用 Firebase 的应用程序应该支持它,否则用户会在某些时候陷入困境。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建 Firebase Web user.reauthenticateWithCredential() 方法所需的“凭据”对象? 的相关文章

随机推荐