authentication - Ionic Framework 和 Firebase 持久身份验证

标签 authentication ionic-framework firebase ng-storage

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

使用 $authWithPassword 登录后,回调包括 uid 和 token 。如果我使用 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 和 token 持续进行身份验证。没有用户密码是否可以做到?

在此先感谢您的帮助。

最佳答案

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

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

当我第一次尝试作为新手开发者时,我自己并不明显,但保存的 token 可用于在每次打开应用程序时重新登录用户。

在 ionic 应用程序的 .run() 部分,注入(inject) $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');
}

总而言之,如果有一个 token 保存到 localstorage,使用它通过 firebases $authWithCustomToken() 登录。

关于authentication - Ionic Framework 和 Firebase 持久身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35637492/

相关文章:

php - 如何将 mysql 转换为 mysqli

ios - 导航被拒绝 - <allow-navigation> 没有为 url ='gap://ready' 设置

android - Firebase 不从控制台发送通知

javascript - 使用 Polymerfire 保存文档时出现问题

python - (401) 未经 python-firebase 授权

authentication - Capistrano 无法部署到新的 Ubuntu 服务器,因为 SSHKit/Net::SSH 无法进行身份验证

angular - 使用ionic 4 cordova仅从设备存储中获取音频文件

android - 带有 FCM 的 firebase 实时数据库用于实现聊天

forms - 我可以使用css3制作这个银色渐变效果的登录表单吗?

node.js - 使用 Ionic 连接到 MongoDB 远程服务器