Firebase Admin SDK - Check user's password against variable on server
Asked Answered
M

2

6

I am trying to implement a feature for a user to change their password in their settings page when they are logged in, and I require the user's old password as well as the new password when they try to change it as an extra security measure. My problem is that I cannot find a way to verify if the user's old password is correct. Is there an easy way to do this?

I receive the entered form inputs on the server so the solution would have to be on the backend (node.js)

Many thanks

Mitre answered 26/9, 2018 at 17:39 Comment(0)
W
5

You have to do it client side. This is not an operation that the admin SDK is designed to handle. You will ask the current user for the password and reauthenticate with it and then update password:

const cred = firebase.auth.EmailAuthProvider.credential(
    firebase.auth().currentUser.email, oldPass);
firebase.auth().currentUser.reauthenticateWithCredential(cred)
  .then(() => {
    return firebase.auth().currentUser.updatePassword(newPass);
  })
  .catch((error) => {
    // Some error.
  });
Winther answered 28/9, 2018 at 0:46 Comment(0)
E
7

Though the accepted solution works, there is also a way to verify a user's password from the backend, using the Google Identity Kit REST API's "verifyPassword" endpoint (which has recently been renamed to "signInWithPassword", but works exactly the same):

HTTP POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[YOUR_FIREBASE_API_KEY]
{
  email,
  password,
}

If that endpoint doesn't return an error, that means the password is valid.

See this thread for more information.

Eridanus answered 2/9, 2021 at 17:59 Comment(1)
Super-helpful, @Adam! I was pulling out my hair looking for a server-side solution. This worked for me. Thank you!Cerous
W
5

You have to do it client side. This is not an operation that the admin SDK is designed to handle. You will ask the current user for the password and reauthenticate with it and then update password:

const cred = firebase.auth.EmailAuthProvider.credential(
    firebase.auth().currentUser.email, oldPass);
firebase.auth().currentUser.reauthenticateWithCredential(cred)
  .then(() => {
    return firebase.auth().currentUser.updatePassword(newPass);
  })
  .catch((error) => {
    // Some error.
  });
Winther answered 28/9, 2018 at 0:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.