Firebase JWT身份验证,连续发送令牌?
问题描述:
嗨我是Firebase的新手,但非常喜欢它。Firebase JWT身份验证,连续发送令牌?
我看过这个:https://www.firebase.com/docs/security/custom-login.html,我能够成功地创建一个JWT并对我的Firebase帐户进行身份验证。好极了!
但是,我不确定这对未来的后续调用Firebase意味着什么。我是否需要将此令牌传递给Firebase以后的所有请求?
答
未来在同一页面内调用Firebase将使用相同的身份验证。来自文档:
对任何引用进行身份验证都会将该客户端认证为整个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;
}
}