3
votes

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:

  • authenticate user using Firebase built-in providers (purely client side)
  • obtain Firebase JWT (my question)
  • pass this JWT as/whenever needed, to external service and verify it (using my app FBase secret) for "access" to external service

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!

5

5 Answers

5
votes

This is the right way to obtain firebase JWT token

firebase.auth().currentUser.getToken().then(function(token){
  console.log(token);
});
2
votes

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
2
votes

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
            }
        })
2
votes

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();
1
votes

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