Klowne
Klowne

Reputation: 59

Getting and Sending Firebase Realtime Database Auth Token with $http.get (Vue-Resource) in Vue

I think I fundamentally misunderstand how this works and I have got myself into a loop. I've spent two days trying to work it out but I think I am stuck and need some help getting back onto the right track.

I have a FB Realtime Database with these rules:

{
  "rules": {
      // any logged-in user access your data
      ".read": "auth != null",
      ".write": "auth != null"
    
   }
}

I can register users and log them in. But I cannot seem to work out how to get a token and then send it along with my $http.get requests. At the moment I am checking for an auth() change, but I am a little bit confused as to which one is the token that I should send along with the request. A few things I have found say I should use the refreshToken:

firebase.auth().onAuthStateChanged(user => {
    store.dispatch("updateUserStore", {'token': user.refreshToken, 'uid': user.uid});
});

The token and UID is then stored in my Vuex store - but when I send the token I get this response:

this.$http.get('users/'+uid+'.json?auth='+token)
    .then(response => {
        return response.json();
    })
    .then(data => {
        // do something
    });

Response:

{error: "Could not parse auth token."}

I have searched the error and tried to follow as much of the help as possible but none of it seems to help. I know I can use Axios instead but I would like to understand why this doesn't work rather than avoid the issue, as there is obviously something I do not understand happening here.

Thank you in advance!

Upvotes: 0

Views: 1394

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83153

As explained in the REST API doc, you need to "follow the steps in Retrieve ID tokens on clients."

So, you should do as follows (untested):

firebase.auth().onAuthStateChanged(user => {
    user.getIdToken(/* forceRefresh */ true)
      .then(idToken => {
         store.dispatch("updateUserStore", {'token': idToken, 'uid': user.uid});
      }).catch(function(error) {
         // Handle error
      });
});

HOWEVER, note that ID tokens expire after a short period of time (one hour), so it is probably not a good idea to store them in a Vuex store when the user's sign-in state changes (i.e. through onAuthStateChanged). As a matter of fact the token may expire without any change to the user's sign-in state.

Upvotes: 2

Related Questions