Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase getToken() TypeError: Cannot read property

I'm trying to get the token of my currently signed in user of my website. However, javascript cannot get the value for me. I think there are 2 problems here:

  1. When I'm getting Auth.currentUser at start, I get this error of "TypeError: Cannot read property 'getToken' of null". But when I type Auth.currentUser.getToken() in the console, the object with the token actually shows up.

  2. What getToken() returns to me is a promise object with its key 'ea' containing the value of the token. but when I do Auth.currentUser.getToken().ea it gets me 'null'. How can I retrieve the token directly from the object?

Thanks!

My code of retrieving the token:

var Auth = firebase.auth()
var token = Auth.currentUser.getToken()

This screenshot might be helpful: Chrome console result

like image 915
thousight Avatar asked Jun 21 '16 03:06

thousight


2 Answers

According to the documentation of firebase.User:getIdToken():

Returns a JWT token used to identify the user to a Firebase service.

Returns the current token if it has not expired, otherwise this will refresh the token and return a new one.

The method returns a promise, since it may require a round-trip to the Firebase servers in case the token has expired:

Auth.currentUser.getIdToken().then(data => console.log(data))

Or in more classic JavaScript:

Auth.currentUser.getIdToken().then(function(data) {
    console.log(data)
});

Log output:

ey...biPA

Update: to ensure that the user is signed in before getting the token, run the above code in an onAuthStateChanged listener:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    user.getIdToken().then(function(data) {
      console.log(data)
    });
  }
});
like image 109
Frank van Puffelen Avatar answered Nov 03 '22 04:11

Frank van Puffelen


Here is a sample on how to get the id token using NodeJS

var firebase = require('firebase')
firebase.initializeApp({
    apiKey:*********
    databaseURL:*********
})

var customToken = *********    
firebase.auth().signInWithCustomToken(customToken).catch(function(error) {
    var errorMessage = error.message
    console.log(errorMessage)
})

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        firebase.auth().currentUser.getToken().then(data => console.log(data))
    } else {
        console.log('onAuthStateChanged else')
    }
})
like image 33
Mike Yang Avatar answered Nov 03 '22 04:11

Mike Yang