3

我想知道是否有人使用过 ionic 和 firebase 并允许持久身份验证。当我创建 IPA/APK 并将应用程序下载到我的设备时,每次关闭应用程序时我都必须重新登录。

使用 $authWithPassword 登录后,回调包括 uid 和令牌。如果我使用 get import ngStorage 作为依赖项,我如何使用 uid 和 token 来持久化身份验证?

对于登录,用户登录调用登录函数,该函数链接到我工厂的 Auth.login 函数。

    login: function(user) {
        return auth.$authWithPassword({
            email: user.email,
            password: user.password
        }, function(error, authData) {
            switch(error.code) {
                case "INVALID_EMAIL":
                    console.log("Log in with a valid email.");
                    break
                case "INVALID_PASSWORD":
                    console.log("Password or email is incorrect");
                    break
                default:
                    console.log("Enter a valid email and password");
            }
        })
        .then(function(authData) {
            console.log("login: Logged in with uid: ", authData);
            $localStorage.uid = authData.uid;
            $localStorage.token = authData.token;

        })
        .catch(function(error) {
            alert("Error: " + error);
        });

我不确定如何使用 uid 和令牌保持身份验证。是否可以在没有用户密码的情况下执行此操作?

提前感谢您的帮助。

4

1 回答 1

3

很久以前我确实找到了答案,但忘了在这里更新。希望它对使用带有 ionic 框架的 firebase auth 的人有用。

如问题部分所示,只需确保在登录时保存令牌。这也适用于 firebase 提供的社交媒体登录。

当我作为第一次开发人员第一次尝试时,这对我自己来说并不明显,但是每次打开应用程序时,可以使用保存的令牌重新登录用户。

在 ionic 应用程序的 .run() 部分,注入 $localStorage、$firebaseAuth 和 $state 添加以下内容:

if($localStorage.token) {
  var token = $localStorage.token;

  var ref = new Firebase('https://yourfirebaselink.firebaseio.com/');

    var auth = $firebaseAuth(ref);

  auth.$authWithCustomToken(token, function(error, authData) {
    if (error) {
      console.log("Authentication Failed!", error);
    } else {
      console.log("Authenticated successfully with payload:", authData);
    }
  }).then(function(authData) {
    $state.go('main');
    return true;
  }).catch(function(error) {
    console.log("Please sign in", error);
    delete $localStorage.uid;
    delete $localStorage.token;
  });

} else {
  $state.go('login');
  console.log('not logged in');
}

总之,如果有一个令牌保存到 localstorage,请使用它使用 firebases $authWithCustomToken() 登录。

于 2016-04-19T22:18:07.980 回答