Reputation: 12341
Early into Firebase docs and really liking it so far. Being n00b, a conceptual question here - is the (JWT) token generated by Firebase authentication accessible client-side?
I'm looking to call some external service and want to leverage JWT as the security mechanism. So:
In essence, leverage existing Firebase mechanisms as a form of "gateway" to external service(s).
I saw an old answer here - "....token to survive page reloads, then you need to store it in some way so the client..." - is this token
the JWT
?
Thanks!
Upvotes: 7
Views: 20668
Reputation: 317
Update March 2021:
getToken()
won't work, refer documentation
we have to use getIdToken()
The below version will work in Javascript
firebase.auth().currentUser.getIdToken(true).then(function(token){
console.log(token);
});
Upvotes: 7
Reputation: 17566
Answer for November 2020
Once you have the FirebaseAuth instance, you can get the token using one line of code:
FirebaseAuth auth;
String token;
token = await auth.currentUser.getIdToken();
Upvotes: 3
Reputation: 2398
For any future SO-goers looking to do this in Swift 4, here's a snippet to make your lives easier:
// Force refresh from Firebase if token is expired (pass true)
// or deliberately do not refresh if expired (pass false)
Auth.auth().currentUser?.getIDTokenForcingRefresh(true, completion: { (token, error) in
if error != nil {
print("Network Auth Error: \(String(describing: error?.localizedDescription)))")
} else {
// do something with token
}
})
// If you don't care about the refresh
Auth.auth().currentUser?.getIDToken(completion: { (token, error) in
if error != nil {
print("Network Auth Error: \(String(describing: error?.localizedDescription)))")
} else {
// do something with token
}
})
Upvotes: 2
Reputation: 384
This is the right way to obtain firebase JWT token
firebase.auth().currentUser.getToken().then(function(token){
console.log(token);
});
Upvotes: 7
Reputation: 598603
Firebase indeed keeps the JWT in local storage.
JSON.parse(localStorage.getItem("firebase:session::<app-name>")).token
You can also get it from the authData, where it is available as the value of the token
property.
ref.onAuth(function(authData) { console.log(authData.token); })
But the preferred way is to do what Chris said in the comments:
ref.getAuth().token
Upvotes: 3