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:
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.
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:
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')
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With