How do I get the current user's access token in AngularFire2?

你离开我真会死。 提交于 2019-12-03 06:59:26

getToken is deprecated now. You should use getIdToken instead:

this.af.auth.currentUser.getIdToken(true)
  .then((token) => localStorage.setItem('tokenId', token));

The access token is only accessible when the user first signs in. From the Firebase migration guide for web developers:

With the Firebase.com Authentication API, you can easily use the provider's access token to call out to the provider's API and get additional information. This access token is still available, but only immediately after the sign-in action has completed.

var auth = firebase.auth();

var provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider).then(function(result) {
  var accessToken = result.credential.accessToken;
});

So it is indeed not available on a page refresh. If you want it to remain available, you will need to persist it yourself.

This works for me:

this.af.auth.getAuth().auth.getToken(false);//true if you want to force token refresh

You can put it into a Service and then you can get the token like this:

this.authService.getToken().then(
  (token) => console.debug(`******** Token: ${token}`));

With AngularFire2, you can get the token like this :

this.af.auth.getToken() // returns a firebase.Promise<any>

If you want to get an ES6 Promise instead, just use

Promise.resolve()
  .then(() => this.af.auth.getToken() as Promise<string>)
Freedo AI

googleSignIn() {

    return this.af_auth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider())
      .then(res => {

        // retrieve access token 
        const AccessToken = res.credential['accessToken'];
        console.log("Access token: ", AccessToken);


      })
      .catch(error => {
        console.log(error.message);
      });

Getting the auth token from storage in angularfire2

JSON.parse(JSON.stringify(this.afAuth.auth.currentUser)).stsTokenManager.accessToken

As seen in this discussion: https://github.com/angular/angularfire2/issues/725

With AngularFire2 : ( eg : registering user with email and password combo. )

import { AngularFireAuth } from 'angularfire2/auth';
model : any = {} ;
private afAuth : AngularFireAuth,

regWithEP () {
    this.afAuth.auth.createUserWithEmailAndPassword(this.model.email, this.model.password).then((user) => {
    /* IMPORTANT !! */
    /* EXPLICIT CHECK IF USER IS RETURNED FROM FIREBASE SERVICE !! */

          if (user) {
            console.log(user);
            /* Here user is available and is the same as auth.currentUser */

            this.afAuth.auth.currentUser.getToken().then((token) => {

            //token is available here
            //set token to currentUser, signIn , re-direct etc.
            });
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!