Get Google access token
Asked Answered
R

1

9

To get Google access token after firebase auth login, I know I can simply do this:

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

but what if the user is already authenticated and I need the token? is there any way to extract it from the Firebase auth?

I've been through every value of authState but I couldn't find the google access token I've been looking for.

Rushton answered 11/6, 2017 at 13:33 Comment(0)
B
11

You can't get the access token from the onAuthStateChanged listener or the currentUser. You can only get it immediately after authentication when calling signInWithPopup, reauthenticateWithPopup, linkWithPopup, getRedirectResult, etc. Firebase Auth does not manage OAuth tokens for users. If you feel strongly about this feature, please file a feature request for it on the Firebase forum: https://groups.google.com/forum/#!forum/firebase-talk

You can also just use the GApi library to get the Google access token and pass it to Firebase to sign-in via signInWithCredential. The advantage here is that GApi will manage that OAuth token for you.

Bili answered 12/6, 2017 at 5:34 Comment(2)
Thanks! I tried: let token = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token; this.afAuth.auth .signInWithCredential(token) but it says "credential" must be a valid credential.. Any idea what I have to pass to this method in order to authenticate?Rushton
You can't just pass a plain ID token, you have to wrap it in a credential. signInWithCredential(firebase.auth.GoogleAuthProvider.credential(token))Bili

© 2022 - 2024 — McMap. All rights reserved.