【问题标题】:Firebase JWT Authentication, Continually Send Token?Firebase JWT身份验证,持续发送令牌?
【发布时间】:2013-08-19 20:33:33
【问题描述】:

您好,我是 Firebase 的新手,但非常喜欢它。

我读到:https://www.firebase.com/docs/security/custom-login.html,我能够成功创建 JWT 并针对我的 Firebase 帐户进行身份验证。耶!

但是,我不确定这对以后调用 Firebase 意味着什么。我是否需要在以后向 Firebase 的所有请求中传递此令牌?

【问题讨论】:

    标签: authentication firebase jwt


    【解决方案1】:

    未来在同一页面内调用 Firebase 将使用相同的身份验证。来自文档:

    对任何引用进行身份验证都会对该客户端进行整个 Firebase 的身份验证,如果其互联网连接丢失,Firebase 将再次无缝处理身份验证,因此您只需在应用中执行一次该操作。要更改客户端的凭据(例如,当用户登录到其他帐户时),只需使用新令牌重新进行身份验证即可。

    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)
    

    如果您希望此令牌在页面重新加载后仍然存在,那么您需要以某种方式存储它,以便客户端可以在新页面上调用 firebaseRef.auth(...)。

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

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 2020-07-07
      • 2019-08-04
      • 2019-01-22
      相关资源
      最近更新 更多