如何验证用户当前密码?

33

也许我在文档中错过了这一点,但是我找不到任何相关的内容。

我希望我的用户必须输入他们当前的密码才能创建一个新的密码。据我所知,如果用户已经通过身份验证,则可以更新密码而无需提供当前密码。

尽管这可能相对安全,但我宁愿让他输入旧密码以防止其他人利用已经经过身份验证的会话(例如家庭成员等)并更改密码。

有什么方法可以做到这一点吗?

(我使用Admin SDK没有问题,因为我已经为这些事情设置了服务器)


通常情况下,您会在代码中强制执行此行为。您允许用户访问控制台吗?您的代码库是什么? - Jay
据我所知,Firebase不会提供用户密码,这是可以理解的,我只需要验证。我的用户只有电子邮件/密码,并通过Firebase方法signInWithEmailAndPassword()正常进行身份验证。如果有影响的话,我在服务器端使用Node,在客户端使用React。 - ThatBrianDude
2个回答

46

更新:(使用 - reauthenticateWithCredential)

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

// Prompt the user to re-provide their sign-in credentials

user.reauthenticateWithCredential(credential).then(function() {
  // User re-authenticated.
}).catch(function(error) {
  // An error happened.
});

先前版本

您可以使用重新验证 API 来实现此目的。我假设您想在允许用户更新密码之前验证当前用户的密码。这样,在 Web 中,您可以执行以下操作:

reauthenticateAndRetrieveDataWithCredential- 已弃用

firebase.auth().currentUser.reauthenticateAndRetrieveDataWithCredential(
  firebase.auth.EmailAuthProvider.credential(
    firebase.auth().currentUser.email, 
    providedPassword
  )
);

如果这成功了,那么你就可以调用

firebase.auth().currentUser.updatePassword(newPassword);

1
firebase.User.prototype.reauthenticate已被弃用,建议使用firebase.User.prototype.reauthenticateWithCredential。因此,请使用reauthenticateWithCredential。 - Shyam
1
这样复制粘贴代码片段真是太愉快了...谢谢 :) - Jeremy Belolo
reauthenticateAndRetrieveDataWithCredential 现已弃用,请使用 reauthenticateWithCredential。 - alaswer
如果账户因为太多次错误尝试而被锁定,那该怎么办?用户只是想更改密码,却因此无法再登录您的应用程序。 - Tom3652
这是否仍然为客户留下了通过 Firebase API 更新密码而无需访问我的服务器的选项?(通过API而不是通过我的UI)。这个解决方案是否真正强制用户提供旧密码? - ThatBrianDude
1
请注意,在新的v9 API中,用户对象上不再提供此方法,您应该单独导入它:https://firebase.google.com/docs/reference/js/auth#reauthenticatewithcredential - Slavik Shynkarenko

1
主要的答案对我没用。我觉得它已经过时了。这是对我有效的方法。
步骤1:获取授权
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const app = initializeApp({
  apiKey: "Enter your Api key",
  authDomain: "Enter your Auth domain",
  projectId: "Enter your Project id",
  storageBucket: "Enter your Storage bucket",
  messagingSenderId: "Enter Message Sender Id",
  appId: "Enter your App Id",
});

const auth = getAuth(app);

第二步:获取凭据
import { EmailAuthProvider } from "firebase/auth";

const user = auth.currentUser
const passwordEnteredByUser = formPassword //get password from user using a form
const credential = EmailAuthProvider.credential(
  user.email,
  passwordEnteredByUser
);

第三步:使用凭据验证密码。
import { reauthenticateWithCredential } from "firebase/auth";

reauthenticateWithCredential(user, credential)
.then((result) => {
   //Password entered is correct
   console.log(result)
})
.catch((error) => {
   //Incorrect password or some other error
   console.log(error)
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接