2013-08-17 2 views
3

안녕하세요, 저는 Firebase을 처음 접해 보았지만 정말 좋아했습니다.Firebase JWT 인증, 계속 토큰 보내기?

나는 이것을 읽었습니다 : https://www.firebase.com/docs/security/custom-login.html 그리고 성공적으로 JWT를 만들고 내 Firebase 계정에 인증 할 수 있습니다. 예!

그러나 Firebase에 대한 이후의 호출에 대해 이것이 무엇을 의미하는지 확신 할 수 없습니다. 앞으로의 모든 Firebase 요청에이 토큰을 전달해야합니까?

답변

7

같은 페이지 내에서 향후 Firebase을 호출해도 동일한 인증이 사용됩니다. 문서에서 :

모든 참조를 인증하면 해당 클라이언트가 전체 Firebase에 인증되고 Firebase가 인터넷 연결이 끊어지면 인증이 원활하게 처리되므로 앱에서 한 번만 작업을 수행하면됩니다. . 클라이언트의 자격 증명을 변경하려면 (예를 들어 사용자가 다른 계정에 로그인 할 때) 새 토큰으로 다시 인증하기 만하면됩니다. 이 토큰이 페이지를 다시로드 생존하려면 클라이언트가 새 페이지에 firebaseRef.auth (...)를 호출 할 수 있도록

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) 

는, 당신은 어떤 방법으로 보관해야합니다.

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