Shady Aziza
Shady Aziza

Reputation: 53307

How to get the ID token from FirebaseAuth

I am reading some Json files from my firebase database and I am trying to obtain an ID token for the current user to be used in the header as follows:

 var response = await httpClient.get(url,headers: {'Authorization':"Bearer ${FirebaseAuth.instance.currentUser.getToken()}"});

when I do the previous line, it seems that it does not get the correct token as I can not access the database, however, when I manually include an ID token in the string, my application works as intended. What is it exactly that I am doing wrong ?

Upvotes: 20

Views: 73267

Answers (4)

Kashif Ahmed
Kashif Ahmed

Reputation: 833

If you are working with

import auth from '@react-native-firebase/auth';

then you can access the token with

var token = await response.user.getIdToken();
console.log('TokenID', token);

and after that, you can use it into

var response = await httpClient.get(url,headers: {'Authorization':"Bearer $token"});

Upvotes: 0

Matteo Antolini
Matteo Antolini

Reputation: 3068

I think that there is a bug in Flutter.

Now to call the method getIdToken() you need to do this:

FirebaseUser user = await FirebaseAuth.instance.currentUser();

String token;

user.getIdToken().then((result) {

    token = result.token;
});

You can't call FirebaseAuth.instance.currentUser().getIdToken()

Upvotes: 6

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

getIdToken() returns a Future - you have to await it to actually get the token string:

var token = await FirebaseAuth.instance.currentUser().getIdToken();
var response = await httpClient.get(url,headers: {'Authorization':"Bearer $token"});

Upvotes: 38

Rilliano Mertodikromo
Rilliano Mertodikromo

Reputation: 11

U can also retrieve the id token from the window object like so:

const idToken = window.gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token

Upvotes: 1

Related Questions