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:
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)
});
}
});
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')
}
})