質問

Hi I am new to Firebase but really liking it.

I read this: https://www.firebase.com/docs/security/custom-login.html and I am able to successfully create a JWT and authenticate against my Firebase account. Yay!

However I am not sure what this means for future, subsequent calls to Firebase. Do I need to pass this token in all future requests to Firebase?

役に立ちましたか?

解決

Future calls to Firebase within the same page will utilize the same authentication. From the docs:

Authenticating on any reference will authenticate that client to the entire Firebase, and Firebase will seamlessly handle authenticating again if its internet connection is ever lost, so you'll only need to perform the operation once in your app. To change a client's credentials (for example, when a user logs in to a different account), simply re-authenticate with a new token.

var ref = new Firebase(URL);

ref.on('value', ...) // not authenticated

ref.auth(TOKEN, function(error) {
    if( !error ) {
       ref.on('value', ...); //authenticated

       ref.child('...').on('value', ...); //also authenticated

       new Firebase(URL); // also authenticated if I'm using the same URL
    }
});

ref.on('value', ...); // probably not authenticated (async call to auth probably not completed)

If you want this token to survive page reloads, then you need to store it in some way so the client can call firebaseRef.auth(...) on the new page.

var ref = new Firebase(URL);

// fetch a token stored in localStorage on a previous page load
var token = localStorage.getItem('token');
if( !token || !tokenHasTimeLeft(token) ) { 
    token = fetchTokenFromServer(); /* some API call to your custom auth server */-
}
login(token);

function login(token) {
   ref.auth(token, function(error) {
       /** handle errors */
       localStorage.setItem('token', token); // store for future page loads
   });
}

// this method uses Base64.decode by Fred Palmer 
// https://code.google.com/p/javascriptbase64/
// it checks to see if the token stored has more
// than 12 hours left before it expires
function tokenHasTimeLeft(tok) {
      try {
         var body = JSON.parse(Base64.decode(tok.split('.')[1]));
         var exp = body.exp? moment.unix(body.exp) : moment.unix(body.iat).add('hours', 24);
         DEVMODE && console.log('parsed token', body);
         return exp.diff(moment(), 'hours') > 12;
      }
      catch(e) {
         console.warn(e);
         return false;
      }
   }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top