gpt4 book ai didi

authentication - Firebase JWT 认证,不​​断发送 token ?

转载 作者:行者123 更新时间:2023-12-01 09:59:33 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

在任何引用上进行身份验证都会向整个 Firebase 验证该客户端,并且如果其互联网连接丢失,Firebase 将无缝地再次处理身份验证,因此您只需在您的应用中执行一次该操作。要更改客户端的凭据(例如,当用户登录到不同的帐户时),只需使用新 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)

如果您希望此 token 在页面重新加载后仍然存在,则需要以某种方式存储它,以便客户端可以在新页面上调用 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;
}
}

关于authentication - Firebase JWT 认证,不​​断发送 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18290197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com