未来在同一页面内调用 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;
}
}