angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

How to create “credential” object needed by Firebase web user.reauthenticate() method?

Open shamrozwarraich opened this issue 10 years ago • 19 comments

The (unclear) example in the new docs:

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

With the v3 Firebase client, how should I create this credential object?

I tried:

  • reauthenticate(email, password) (like the login method)
  • reauthenticate({ email, password }) (the docs mention one argument only)
  • const credential = firebase.auth.EmailAuthProvider.credential(user.email, userProvidedPassword); (getting error credential does not exit on EmailAuthProvider )

No luck :( #askfirebase

shamrozwarraich avatar Sep 02 '16 12:09 shamrozwarraich

@davideast :/

shamrozwarraich avatar Sep 11 '16 05:09 shamrozwarraich

@shamrozwarraich Why do you need to reauthenticate? The token will refresh indefinitely.

davideast avatar Sep 14 '16 11:09 davideast

am updating the user password and its must required to Re-authenticate the user. but in Re-authenticate method what does credential means,,,,? as in login method we provide user email and password ...

shamrozwarraich avatar Sep 15 '16 06:09 shamrozwarraich

an using this piece of code but getting error on credential... firebase.auth.EmailAuthProvider.credential('[email protected]','existingPassword');

Property 'credential' does not exist on type 'typeof EmailAuthProvider'

shamrozwarraich avatar Sep 16 '16 16:09 shamrozwarraich

Hello @shamrozwarraich , I got it like this:

removeUser(password: string) {
  this.af.auth.take(1).subscribe(user => {
    const credential = firebase.auth.EmailAuthProvider.credential(user.auth.email, password);
    user.auth.reauthenticate(credential).then(() => {
      user.auth.delete();
    });
  });
}

I don't know if it's the best way, but it works

damsorian avatar Oct 18 '16 15:10 damsorian

if its work ... its aa best way :p

On Tue, Oct 18, 2016 at 8:18 PM, Cristian Urbano [email protected] wrote:

Hello @shamrozwarraich https://github.com/shamrozwarraich , I got it like this:

removeUser(password: string) { this.af.auth.take(1).subscribe(user => { const credential = firebase.auth.EmailAuthProvider.credential(user.auth.email, password); user.auth.reauthenticate(credential).then(() => { user.auth.delete(); }); }); }

I don't know if it's the best way, but it works

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/angular/angularfire2/issues/491#issuecomment-254540779, or mute the thread https://github.com/notifications/unsubscribe-auth/AM3xqLShr6YQ7DTsCJs1ZNGxRx0IjiKkks5q1OM6gaJpZM4Jzrci .

shamrozwarraich avatar Oct 19 '16 01:10 shamrozwarraich

Same error for me (referring to original post):

I'm trying to implement Change Email/Change Password functions, which need (according to official documentation) a reauthentication providing a credential object.

Snippet of code:


constructor(
    private router: Router,
    private AF : AngularFire,
    private FiBAuth: FirebaseAuth,
    @Inject(FirebaseApp) private firebaseApp :any  //Should give me access to native firebase instance
  ){
...
}

...
changeUsernameAndPassword(loginData: AppUser, newUser: AppUser, changePassword: boolean): Promise<{'ok': boolean, 'message': string, 'warn': boolean}>{
    const doEmail = (loginData.email != newUser.email);
    const credentials = this.firebaseApp.auth().EmailAuthProvider.credential(loginData.email, loginData.password);
//ERROR: Property 'credential' does not exist...
//Debug: this.firebaseApp.auth().EmailAuthProvider => undefined !! (shouldn't be I suppose)
//Debug: this.firebaseApp.auth() => Object
...
  }

For the solution of @cristianurbano ... you use: firebase.auth.EmailAuthProvider ... but how do you get a reference to the "firebase" instance? If you use AngularFire2 you should get a reference with @Inject(FirebaseApp) firebaseApp which should wrap the original SDK object...

gepisolo avatar Jan 25 '17 15:01 gepisolo

@gepisolo I'm still having trouble with this. Any thoughts about this error I'm getting?

import {AngularFireAuth, FirebaseApp} from "angularfire2";
// ...
constructor(private auth: AngularFireAuth, @Inject(FirebaseApp) private firebaseApp: any) {}
// ...
private submitPassword() {
    this.auth.subscribe(auth => {
        auth.auth.reauthenticate(
            this.firebaseApp.auth.EmailAuthProvider.credential(
                auth.auth.email,
                this.passwordModel.currentPassword
            )
        ).then(
            success => {
                console.log('successfully reauthenticated!');
            },
            error => {
                console.log(error);
            }
        )
    });
}

This compiles fine, but when I execute the function, I get Cannot read property 'credential' of undefined in the browser console. Did you encounter this?

evansalter avatar Jan 28 '17 20:01 evansalter

Yes, the very same error. It looks like FirebaseApp is not exposing all the native functions.

In this case it does not expose EmailAuthProvider class. It's impossible to implement a "Change Password/Email" function so I had to drop Angularfire2 and use only the native firebase SDK...

gepisolo avatar Jan 28 '17 21:01 gepisolo

I had to use the sdk for this but it works fine I think.

    import * as firebase from 'firebase';

    reauthenticateUser(email: string, password: string): Subject<boolean> {

        let subject: Subject<boolean> = new Subject<boolean>();

        // create the credentials from the SDK
        const credentials = firebase.auth.EmailAuthProvider.credential(
            email,
            password
        )

        // reauthenticate
        this.firebaseAuthState.auth.reauthenticate(credentials).then((success) => {
            subject.next(success);
            subject.complete();
        }, (error) => {
            subject.error(error);
        });
 
       return subject;
   }

clark-stevenson avatar Feb 26 '17 17:02 clark-stevenson

Late to the party here, but here's the documented credential() function.

You want to use the Firebase object directly imported from the npm module like clark's example above, not the instance you created.

Like so: Firebase.auth.EmailAuthProvider.credential(.. NOT: firebaseApp.auth()...

pejalo avatar Apr 18 '17 05:04 pejalo

       const credentials = Firebase.auth.EmailAuthProvider.credential(
          user.email,
          this.currentPassword
        );
        user.reauthenticateAndRetrieveDataWithCredential(credentials)
          .then(() => {
            updatePassword(this.newPassword)
              .then(() => {
                app.dialog.alert('your password was successfully changed.');
              })
              .catch(error => app.dialog.alert(error))
          })
          .catch(error => app.dialog.alert(error.message))
      }

YerlinMatu avatar Jul 03 '18 01:07 YerlinMatu

i had the same problem with EmailAuthProvider. the solution i founded is using the Auth().signInWithEmailAndPassword firebase.auth().signInWithEmailAndPassword(this.state.User.email, this.state.OldPassword).then((user)=>{ const use = Db.auth().currentUser; use.updatePassword(this.state.NewPassword).then(() => { console.log("Password updated!"); }).catch((error) => { console.log(error); });
}).catch((error)=>{ console.log(error); alert('studentID or password is wrong'); });

khalidos32 avatar Jul 13 '18 09:07 khalidos32

We were running into a problem where we needed to use EmailAuthProvider.credential(user, pass) but when we tried using the official firebase package as a work around it would freeze up our Ionic production build. The angularfire2 package however wouldn't freeze up our build. This is a known issue that Ionic has with the firebase package that hasn't been fixed yet.

To work around this we ended up creating a fork of angularfire2 that has a emailAuthProviderCredential function on the AngularFireAuth object. It's literally just a pass through that exposes firebase.auth.EmailAuthProvider.credential(user, pass).

Here's the fork: https://github.com/seed2spoon/angularfire2

So, if you absolutely need to create credentials in angularfire2 without installing the firebase package feel free to use this fork via "npm install https://github.com/seed2spoon/angularfire2/releases/download/5.1.1-s2s/5.1.1-s2s.tar.gz"

jswilliams avatar Mar 09 '19 05:03 jswilliams

Is there any specific reason the .credential functions are not exposed in the AngularFire API? @davideast asks why you would need to reauthenticate, but the firebase docs specifically indicate the use of reauthentication prior to sensitive functions, like changing account email or password.

The workarounds above work, but they don't seem to be the best options. You can either just call signInWithEmailAndPassword again, which is not the method indicated in the documentation for this purpose. You can also pull in the raw firebase SDK and call the .credential function from there, but that seems to defeat the purpose of having an Angular wrapper.

The solution @jswilliams provides seems to be the way this should work when using the AngularFIre2 module. Any official thoughts?

Daynil avatar Apr 19 '19 19:04 Daynil

Is there any reason why this hasn't been exposed? I need to convert an anonymous user to a full user. var credential = firebase.auth.EmailAuthProvider.credential(details.email, details.password); return this.afAuth.auth.currentUser.linkAndRetrieveDataWithCredential(credential).then(function (usercred) {

the only way currently is to import * as firebase from 'firebase'; which returns this on build...

It looks like you're using the development build of the Firebase JS SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use.

wallstudios avatar Jun 18 '19 04:06 wallstudios

Is there any reason why this hasn't been exposed? I need to convert an anonymous user to a full user. var credential = firebase.auth.EmailAuthProvider.credential(details.email, details.password); return this.afAuth.auth.currentUser.linkAndRetrieveDataWithCredential(credential).then(function (usercred) {

the only way currently is to import * as firebase from 'firebase'; which returns this on build...

It looks like you're using the development build of the Firebase JS SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use.

For anyone still having this issue, this worked for me:

import { auth } from 'firebase/app';

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

FakeTails avatar May 10 '20 16:05 FakeTails

yesterday this was working perfectly fine..but I think an update of my npm package to the latest version I constantly getting errors. Please angularFirebase fix it and let us know the status. I think I am not able to use almost most of the AuthProviders nowadays.

I have just resolved this issue by

import { auth } from 'firebase/app';
import 'firebase/auth';

iamsrujal avatar May 16 '20 19:05 iamsrujal

I had to use the sdk for this but it works fine I think.

    import * as firebase from 'firebase';

    reauthenticateUser(email: string, password: string): Subject<boolean> {

        let subject: Subject<boolean> = new Subject<boolean>();

        // create the credentials from the SDK
        const credentials = firebase.auth.EmailAuthProvider.credential(
            email,
            password
        )

        // reauthenticate
        this.firebaseAuthState.auth.reauthenticate(credentials).then((success) => {
            subject.next(success);
            subject.complete();
        }, (error) => {
            subject.error(error);
        });
 
       return subject;
   }

This worked for me

0xtruly avatar Sep 13 '20 23:09 0xtruly