Firebase JWT Authentication, Continually Send Token?

前端 未结 1 1924
执笔经年
执笔经年 2021-01-14 13:35

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 au

相关标签:
1条回答
  • 2021-01-14 14:07

    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;
          }
       }
    
    0 讨论(0)
提交回复
热议问题