保持用户登录

时间:2021-03-20 14:40:42

标签: javascript angular firebase ionic-framework firebase-authentication

我正在创建一个 Ionic 应用程序(iOS 和 Android 与 Capacitor)。 我在我的应用程序中添加了 Firebase Auth,但每次退出应用程序时,我都需要重新登录。

我看到了这个,但是没有太多文档,我尝试了但没有用。 我不确定我是否正确使用它或在正确的位置添加了代码。 https://firebase.google.com/docs/auth/web/manage-users?hl=en

我考虑将用户信息保存在本地存储中,当应用程序加载时,检查是否有数据,如果有,将用户移动到主屏幕,否则,呈现登录屏幕。但我不确定这是否是一个好的做法。

这就是我签署用户的方式:

  async googleSignIn() {
    let googleUser = await Plugins.GoogleAuth.signIn();
    let credential = firebase.auth.GoogleAuthProvider.credential(googleUser.authentication.idToken);

    
    let userCredential = await this.afAuth.signInWithCredential(credential);
    return userCredential;
  }

我尝试使用我在 app.component.ts 中的文档中看到的内容,如下所示:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import firebase from 'firebase/app';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})

export class AppComponent {
  rootPage: 'login';
  constructor(private router: Router) { 
    firebase.auth().onAuthStateChanged((user) => {
      if(user) {
        this.router.navigate(['home']);
      } else { 
        this.router.navigate(['login']);
      }
    });
  }
}

它似乎没有“连接”到任何东西,但我找不到太多信息。

1 个答案:

答案 0 :(得分:1)

Firebase Authentication 可以自动保持用户的身份验证状态,并在应用重启/页面重新加载时恢复它。但在某些环境中,默认情况下不启用此功能,您必须按照 auth state persistence 上的文档中所示自行配置。这应该采用以下形式:

Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available. 

之后您的 firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL) 应该开始工作了。

另见:

相关问题