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

7

13

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 initial login say like this:

this.af.auth.subscribe(user=> {
  if (user) {
    console.log(user.google);
  }
});

It will log out the idToken, accessToken, provider, But (on a page refresh) subsequently will log out the standard details (uid, displayName etc....) And the accessToken is not an accessible property?

Is there a way to access the current users accessToken?

Senskell answered 14/10, 2016 at 11:28 Comment(0)
D
7

getToken is deprecated now. You should use getIdToken instead:

this.af.auth.currentUser.getIdToken(true)
  .then((token) => localStorage.setItem('tokenId', token));
Dessau answered 29/6, 2017 at 1:37 Comment(1)
I'm passing "true" into getIdToken, but token doesn't updated forcibly. I'm do login with 2 diff account. Any suggestions? Thanks.Glasses
S
1

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.

Strung answered 14/10, 2016 at 13:6 Comment(4)
No sadly this won't work with the AngularFire2 library.Senskell
Yeah, I don't get it either. It looks like login() resolves with different data than signInWithPopup().Strung
In the end I am just using the Firebase SDK to get the token and then persist it in localStorage. I found I had to not initialise the AngularFire2 straight away as it gets a bit funky (if the current user is still within Firebase's auth period), and then perhaps lazy load this (AngularFire2) later.Senskell
How did you manage to use the Firebase Native SDK finally? I'm struggling to get this work because the AngularFire2 login method seems to really modify the original one.Baillargeon
S
1

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>)
Sardou answered 21/2, 2017 at 13:11 Comment(0)
S
1

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}`));
Sparkie answered 23/2, 2017 at 5:53 Comment(2)
This is the problem with getAuth() though....the getAuth() API has changed behavior since adding support for Firebase 3. This will return null for the initial value when the page loads, even if the user is actually logged in. Please observe the actual authState asynchronously by subscribing to the auth service: af.auth.subscribe(). The getAuth method will be removed in future releasesSenskell
I know that the documentation say this but my solution is working fine. The only problem is a warning mention that this will work in the future as you said but don't worry because in that moment will exist other new method or alternative solution to use.Sparkie
P
0

I was facing difficulty accessing the access token (res.stsTokenManager.accessToken) because it was always returning undefined. To resolve this issue, I implemented the following solution:

this.afAuth.currentUser.then((res: any) => {
  console.log(JSON.parse(JSON.stringify(res))?.stsTokenManager.accessToken);
});

I used the afAuth.currentUser method, which returns a promise that resolves to the current user object. Then, I applied the then function to handle the resolved value. Within the then callback, I converted the user object to a JSON string using JSON.stringify(res). After that, I parsed the JSON string back into an object using JSON.parse. Finally, to access the access token property safely, I used the optional chaining operator (?.) followed by stsTokenManager.accessToken.

By implementing this code snippet, I was able to successfully log the value of the access token from the stsTokenManager object of the current user. This approach helped me avoid any potential errors in case the access token or any intermediate property was undefined.

Philippe answered 17/5, 2023 at 23:48 Comment(0)
P
-1

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

Podgorica answered 21/9, 2019 at 21:42 Comment(0)
T
-3

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.
            });
        }
    });
}
Timework answered 1/6, 2018 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.