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

Created on 2 Sep 2016  Â·  19Comments  Â·  Source: angular/angularfire

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

Most helpful comment

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()...

All 19 comments

@davideast :/

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

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 ...

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'

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

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
.

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 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?

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...

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;
   }

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()...

```const user = account.currentUser;
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))
}

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');
});

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"

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?

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.

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);

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';

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

Was this page helpful?
0 / 5 - 0 ratings