Skip to content Skip to sidebar Skip to footer

How Do I Get The Current User's Access Token In Angularfire2?

In AngularFire you were able to access the providers (e.g Google) accessToken for the authenticated user. There does not seem to be a way to access this with AngularFire2? On initi

Solution 1:

getToken is deprecated now. You should use getIdToken instead:

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

Solution 2:

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.

Solution 3:

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() asPromise<string>)

Solution 4:

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

Solution 5:

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

Post a Comment for "How Do I Get The Current User's Access Token In Angularfire2?"