Firebase getToken() TypeError: Cannot read property

前端 未结 2 740
不知归路
不知归路 2020-12-14 10:23

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:

相关标签:
2条回答
  • 2020-12-14 10:57

    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)
        });
      }
    });
    
    0 讨论(0)
  • 2020-12-14 11:16

    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')
        }
    })
    
    0 讨论(0)
提交回复
热议问题