使用Firebase的authWithOAuthRedirect时如何避免重定向循环

时间:2015-03-24 17:21:50

标签: authentication firebase

我运行了以下代码,导致页面继续尝试重新加载,并且用户似乎永远不会进行身份验证。应该注意的是,使用authWithOAuthPopup方法时,这可以正常工作。

var myDataRef = new Firebase("https://<my-firebase>.firebaseio.com");

var existingAuthData = myDataRef.getAuth(); //After the oauth redirect and every subsequent load, this is always null

//register onAuth listener
myDataRef.onAuth(function(authData) {
    //We never get this far as the page continues to attempt to load
    if (authData !== null){
        console.log('logged in now!')
    }       
    else {
        console.log('not logged in yet')
    }
})

if (existingAuthData !== null) {
    console.log('User already logged in');
}
else {
    console.log('getAuth returned nothing - authenticating');
    myDataRef.authWithOAuthRedirect("github", function(error, authData) {
      if (error) {
        console.log("Login Failed!", error);
      } else {
        console.log("Authenticated successfully with payload:", authData);
      }
    });
}

使用github进行身份验证后,页面将被重定向回我的自定义域,并附加一个哈希:#&__firebase_request_key=Qwnn9TtM2fsIHq44vhCcbXbPa0DMPL1N

然后页面重新加载,只留下url中的#,然后再次使用firebase_request_key哈希重新加载。这无限期地持续下去。

同样,值得注意的是,如果我为authWithOAuthRedirect切换authWithOAuthPopup方法,这会按预期工作。

如何让重定向方法按照我期望的方式工作?

3 个答案:

答案 0 :(得分:4)

使用ref.getAuth()时,您无法使用同步ref.authWithOAuthRedirect来监控身份验证状态。您必须使用ref.onAuth(<callback>)来监控身份验证状态。例如:

    //create your root reference
    var rootRef = new Firebase('https://example.firebaseio.com/');

    // Create a callback which logs the current auth state
    function authDataCallback(authData) {
        if (!authData) {
            console.log(authData);
            rootRef.authWithOAuthRedirect("github", function (error) {
                console.log("Login Failed!", error);
            });
        }
        else {
            console.log("Authenticated successfully with payload:", authData);
        }
    }

    rootRef.onAuth(authDataCallback);

答案 1 :(得分:2)

我遇到了同样的问题,似乎是竞争条件。使用setTimeout()稍微延迟auth已经有所帮助。

这样的事情:

var onAuthCallback = function(authData) {
  if (!authData) {
    rootRef.authWithOAuthRedirect("google", function (error) {
      console.log("Login Failed!", error);
    });
  }
  else {
    console.log("Authenticated successfully with payload:", authData);
    rootRef.offAuth(onAuthCallback);
  }
};

// Important: don't request authentication immediately
setTimeout(function() { rootRef.onAuth(onAuthCallback); }, 400);

答案 2 :(得分:0)

Firebase版本2.4中已修复此问题。请参阅changelog for javascript api

尝试https://cdn.firebase.com/js/client/2.4.1/firebase.js或更新。